Pin Ruff in pre-commit + add Ruff format to CI (#1633)
* bump ruff version & move to ruff-check * add ruff format to CI * run ruff format * fix ruff --------- Co-authored-by: sami jaghouar <sami@primeintellect.ai>
This commit is contained in:
co-authored by
sami jaghouar
parent
e67022bb3b
commit
bd78508566
@@ -20,3 +20,11 @@ jobs:
|
|||||||
submodules: true
|
submodules: true
|
||||||
- name: Run ruff
|
- name: Run ruff
|
||||||
uses: astral-sh/ruff-action@v3
|
uses: astral-sh/ruff-action@v3
|
||||||
|
with:
|
||||||
|
version: "0.13.0"
|
||||||
|
args: "check --config=pyproject.toml"
|
||||||
|
- name: Run ruff format (check)
|
||||||
|
uses: astral-sh/ruff-action@v3
|
||||||
|
with:
|
||||||
|
version: "0.13.0"
|
||||||
|
args: "format --check --config=pyproject.toml"
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
repos:
|
repos:
|
||||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||||
# Ruff version.
|
# Ruff version.
|
||||||
rev: v0.9.3
|
rev: v0.13.0
|
||||||
hooks:
|
hooks:
|
||||||
# Run the linter.
|
# Run the linter.
|
||||||
- id: ruff
|
- id: ruff-check
|
||||||
args: [ --fix, --config=pyproject.toml ]
|
args: [ --fix, --config=pyproject.toml ]
|
||||||
# Run the formatter.
|
# Run the formatter.
|
||||||
- id: ruff-format
|
- id: ruff-format
|
||||||
|
|||||||
@@ -650,9 +650,7 @@ class OrchestratorConfig(BaseSettings):
|
|||||||
# Whether to reset inference weights to base model when starting from scratch
|
# Whether to reset inference weights to base model when starting from scratch
|
||||||
reload_weights_on_start: Annotated[
|
reload_weights_on_start: Annotated[
|
||||||
bool,
|
bool,
|
||||||
Field(
|
Field(description="Whether to reset inference weights to the base model when starting from scratch."),
|
||||||
description="Whether to reset inference weights to the base model when starting from scratch."
|
|
||||||
),
|
|
||||||
] = True
|
] = True
|
||||||
|
|
||||||
# The validation configuration
|
# The validation configuration
|
||||||
|
|||||||
@@ -196,7 +196,9 @@ class Scheduler:
|
|||||||
wait_for_ckpt_start_time = time.perf_counter()
|
wait_for_ckpt_start_time = time.perf_counter()
|
||||||
await wait_for_path(get_step_path(get_broadcast_dir(self.config.output_dir), next_ckpt_step) / "STABLE")
|
await wait_for_path(get_step_path(get_broadcast_dir(self.config.output_dir), next_ckpt_step) / "STABLE")
|
||||||
self.wait_for_ckpt_time = time.perf_counter() - wait_for_ckpt_start_time
|
self.wait_for_ckpt_time = time.perf_counter() - wait_for_ckpt_start_time
|
||||||
self.logger.info(f"Orchestrator resumed: checkpoint {next_ckpt_step} ready (after {self.wait_for_ckpt_time:.2f}s)")
|
self.logger.info(
|
||||||
|
f"Orchestrator resumed: checkpoint {next_ckpt_step} ready (after {self.wait_for_ckpt_time:.2f}s)"
|
||||||
|
)
|
||||||
|
|
||||||
self.logger.debug(
|
self.logger.debug(
|
||||||
f"Got new policy with step {next_ckpt_step}. Updating weights and cancelling old rollout requests."
|
f"Got new policy with step {next_ckpt_step}. Updating weights and cancelling old rollout requests."
|
||||||
|
|||||||
@@ -71,7 +71,6 @@ def interleave_rollout(state: vf.State) -> list[TrainingSample] | None:
|
|||||||
# New prefix is the current prompt and completion ids concatenated
|
# New prefix is the current prompt and completion ids concatenated
|
||||||
prefix_tokens = tokens["prompt_ids"] + tokens["completion_ids"]
|
prefix_tokens = tokens["prompt_ids"] + tokens["completion_ids"]
|
||||||
|
|
||||||
|
|
||||||
return [interleaved_rollout]
|
return [interleaved_rollout]
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -324,7 +324,6 @@ class RLConfig(BaseSettings):
|
|||||||
batch_size=self.orchestrator.batch_size,
|
batch_size=self.orchestrator.batch_size,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
trainer_bench_enabled = self.trainer.bench is not None
|
trainer_bench_enabled = self.trainer.bench is not None
|
||||||
if trainer_bench_enabled != self.orchestrator.bench:
|
if trainer_bench_enabled != self.orchestrator.bench:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
|
|||||||
@@ -33,13 +33,7 @@ def prepare_sample(
|
|||||||
if teacher_logprobs is not None:
|
if teacher_logprobs is not None:
|
||||||
teacher_logprobs = teacher_logprobs[:seq_len]
|
teacher_logprobs = teacher_logprobs[:seq_len]
|
||||||
|
|
||||||
assert (
|
assert len(input_ids) == len(advantages) == len(loss_mask) == len(position_ids) == len(inference_logprobs), (
|
||||||
len(input_ids)
|
|
||||||
== len(advantages)
|
|
||||||
== len(loss_mask)
|
|
||||||
== len(position_ids)
|
|
||||||
== len(inference_logprobs)
|
|
||||||
), (
|
|
||||||
f"input_ids: {len(input_ids)}, advantages: {len(advantages)}, loss_mask: {len(loss_mask)}, position_ids: {len(position_ids)}, inference_logprobs: {len(inference_logprobs)}"
|
f"input_ids: {len(input_ids)}, advantages: {len(advantages)}, loss_mask: {len(loss_mask)}, position_ids: {len(position_ids)}, inference_logprobs: {len(inference_logprobs)}"
|
||||||
)
|
)
|
||||||
if teacher_logprobs is not None:
|
if teacher_logprobs is not None:
|
||||||
|
|||||||
@@ -46,4 +46,10 @@ def supports_custom_impl(model_config: PretrainedConfig) -> bool:
|
|||||||
return type(model_config) in _CUSTOM_CAUSAL_LM_MAPPING
|
return type(model_config) in _CUSTOM_CAUSAL_LM_MAPPING
|
||||||
|
|
||||||
|
|
||||||
__all__ = ["AutoModelForCausalLMPrimeRL", "PreTrainedModelPrimeRL", "supports_custom_impl", "PrimeLmOutput", "cast_float_and_contiguous"]
|
__all__ = [
|
||||||
|
"AutoModelForCausalLMPrimeRL",
|
||||||
|
"PreTrainedModelPrimeRL",
|
||||||
|
"supports_custom_impl",
|
||||||
|
"PrimeLmOutput",
|
||||||
|
"cast_float_and_contiguous",
|
||||||
|
]
|
||||||
|
|||||||
@@ -11,4 +11,3 @@ __all__ = [
|
|||||||
"AfmoeModel",
|
"AfmoeModel",
|
||||||
"AfmoePreTrainedModel",
|
"AfmoePreTrainedModel",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -4,8 +4,10 @@ from transformers.utils import logging
|
|||||||
|
|
||||||
logger = logging.get_logger(__name__)
|
logger = logging.get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class AfmoeConfig(PretrainedConfig):
|
class AfmoeConfig(PretrainedConfig):
|
||||||
"""Configuration for AFMoE."""
|
"""Configuration for AFMoE."""
|
||||||
|
|
||||||
model_type = "afmoe"
|
model_type = "afmoe"
|
||||||
base_model_pp_plan = {
|
base_model_pp_plan = {
|
||||||
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
||||||
@@ -88,7 +90,8 @@ class AfmoeConfig(PretrainedConfig):
|
|||||||
self.layer_types = layer_types
|
self.layer_types = layer_types
|
||||||
if self.layer_types is None:
|
if self.layer_types is None:
|
||||||
self.layer_types = [
|
self.layer_types = [
|
||||||
"sliding_attention" if bool((i + 1) % global_attn_every_n_layers) else "full_attention" for i in range(self.num_hidden_layers)
|
"sliding_attention" if bool((i + 1) % global_attn_every_n_layers) else "full_attention"
|
||||||
|
for i in range(self.num_hidden_layers)
|
||||||
]
|
]
|
||||||
layer_type_validation(self.layer_types)
|
layer_type_validation(self.layer_types)
|
||||||
|
|
||||||
|
|||||||
@@ -27,22 +27,22 @@ def is_moe_layer_tt(state_dict: dict[str, Tensor], layer_idx: int) -> bool:
|
|||||||
|
|
||||||
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int) -> None:
|
def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int) -> None:
|
||||||
"""Convert a single MoE layer from HF format to TT format in-place.
|
"""Convert a single MoE layer from HF format to TT format in-place.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
state_dict: The state dict to modify in-place.
|
state_dict: The state dict to modify in-place.
|
||||||
layer_idx: The layer index to convert.
|
layer_idx: The layer index to convert.
|
||||||
"""
|
"""
|
||||||
prefix = f"model.layers.{layer_idx}.mlp"
|
prefix = f"model.layers.{layer_idx}.mlp"
|
||||||
|
|
||||||
# Check if this is a MoE layer (has individual experts)
|
# Check if this is a MoE layer (has individual experts)
|
||||||
is_moe_layer = is_moe_layer_hf(state_dict, layer_idx)
|
is_moe_layer = is_moe_layer_hf(state_dict, layer_idx)
|
||||||
if not is_moe_layer:
|
if not is_moe_layer:
|
||||||
return # Dense layer, no conversion needed
|
return # Dense layer, no conversion needed
|
||||||
|
|
||||||
num_experts = get_num_experts_from_state_dict(state_dict, layer_idx)
|
num_experts = get_num_experts_from_state_dict(state_dict, layer_idx)
|
||||||
if num_experts == 0:
|
if num_experts == 0:
|
||||||
return
|
return
|
||||||
|
|
||||||
# Convert shared experts: shared_experts -> shared_expert, gate_proj/up_proj/down_proj -> w1/w3/w2
|
# Convert shared experts: shared_experts -> shared_expert, gate_proj/up_proj/down_proj -> w1/w3/w2
|
||||||
shared_mappings = [
|
shared_mappings = [
|
||||||
(f"{prefix}.shared_experts.gate_proj.weight", f"{prefix}.shared_expert.w1"),
|
(f"{prefix}.shared_experts.gate_proj.weight", f"{prefix}.shared_expert.w1"),
|
||||||
@@ -61,14 +61,14 @@ def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int) -> Non
|
|||||||
("down_proj", "w2"),
|
("down_proj", "w2"),
|
||||||
("up_proj", "w3"),
|
("up_proj", "w3"),
|
||||||
]
|
]
|
||||||
|
|
||||||
for hf_name, tt_name in expert_mappings:
|
for hf_name, tt_name in expert_mappings:
|
||||||
expert_weights = []
|
expert_weights = []
|
||||||
for i in range(num_experts):
|
for i in range(num_experts):
|
||||||
hf_key = f"{prefix}.experts.{i}.{hf_name}.weight"
|
hf_key = f"{prefix}.experts.{i}.{hf_name}.weight"
|
||||||
if hf_key in state_dict:
|
if hf_key in state_dict:
|
||||||
expert_weights.append(state_dict.pop(hf_key))
|
expert_weights.append(state_dict.pop(hf_key))
|
||||||
|
|
||||||
if expert_weights:
|
if expert_weights:
|
||||||
# Stack along first dimension: [num_experts, out_dim, in_dim]
|
# Stack along first dimension: [num_experts, out_dim, in_dim]
|
||||||
stacked = torch.stack(expert_weights, dim=0)
|
stacked = torch.stack(expert_weights, dim=0)
|
||||||
@@ -77,17 +77,17 @@ def convert_hf_layer_to_tt(state_dict: dict[str, Tensor], layer_idx: int) -> Non
|
|||||||
|
|
||||||
def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_idx: int) -> None:
|
def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_idx: int) -> None:
|
||||||
"""Convert a single MoE layer from TT format to HF format in-place.
|
"""Convert a single MoE layer from TT format to HF format in-place.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
state_dict: The state dict to modify in-place.
|
state_dict: The state dict to modify in-place.
|
||||||
layer_idx: The layer index to convert.
|
layer_idx: The layer index to convert.
|
||||||
"""
|
"""
|
||||||
prefix = f"model.layers.{layer_idx}.mlp"
|
prefix = f"model.layers.{layer_idx}.mlp"
|
||||||
|
|
||||||
# Check if this is a MoE layer in TT format
|
# Check if this is a MoE layer in TT format
|
||||||
if not is_moe_layer_tt(state_dict, layer_idx):
|
if not is_moe_layer_tt(state_dict, layer_idx):
|
||||||
return # Dense layer, no conversion needed
|
return # Dense layer, no conversion needed
|
||||||
|
|
||||||
# Convert shared expert: shared_expert -> shared_experts, w1/w2/w3 -> gate_proj/down_proj/up_proj
|
# Convert shared expert: shared_expert -> shared_experts, w1/w2/w3 -> gate_proj/down_proj/up_proj
|
||||||
shared_mappings = [
|
shared_mappings = [
|
||||||
(f"{prefix}.shared_expert.w1", f"{prefix}.shared_experts.gate_proj.weight"),
|
(f"{prefix}.shared_expert.w1", f"{prefix}.shared_experts.gate_proj.weight"),
|
||||||
@@ -97,14 +97,14 @@ def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_idx: int) -> Non
|
|||||||
for tt_key, hf_key in shared_mappings:
|
for tt_key, hf_key in shared_mappings:
|
||||||
if tt_key in state_dict:
|
if tt_key in state_dict:
|
||||||
state_dict[hf_key] = state_dict.pop(tt_key)
|
state_dict[hf_key] = state_dict.pop(tt_key)
|
||||||
|
|
||||||
# Unstack grouped expert weights into individual experts
|
# Unstack grouped expert weights into individual experts
|
||||||
expert_mappings = [
|
expert_mappings = [
|
||||||
("w1", "gate_proj"),
|
("w1", "gate_proj"),
|
||||||
("w2", "down_proj"),
|
("w2", "down_proj"),
|
||||||
("w3", "up_proj"),
|
("w3", "up_proj"),
|
||||||
]
|
]
|
||||||
|
|
||||||
for tt_name, hf_name in expert_mappings:
|
for tt_name, hf_name in expert_mappings:
|
||||||
tt_key = f"{prefix}.experts.{tt_name}"
|
tt_key = f"{prefix}.experts.{tt_name}"
|
||||||
if tt_key in state_dict:
|
if tt_key in state_dict:
|
||||||
@@ -113,7 +113,7 @@ def convert_tt_layer_to_hf(state_dict: dict[str, Tensor], layer_idx: int) -> Non
|
|||||||
for i in range(num_experts):
|
for i in range(num_experts):
|
||||||
hf_key = f"{prefix}.experts.{i}.{hf_name}.weight"
|
hf_key = f"{prefix}.experts.{i}.{hf_name}.weight"
|
||||||
state_dict[hf_key] = stacked[i]
|
state_dict[hf_key] = stacked[i]
|
||||||
|
|
||||||
# Remove TT-specific buffers that don't exist in HF
|
# Remove TT-specific buffers that don't exist in HF
|
||||||
for key in list(state_dict.keys()):
|
for key in list(state_dict.keys()):
|
||||||
if f"{prefix}.tokens_per_expert" in key:
|
if f"{prefix}.tokens_per_expert" in key:
|
||||||
|
|||||||
@@ -206,7 +206,7 @@ class Qwen3MoeConfig(PretrainedConfig):
|
|||||||
self.mlp_only_layers = [] if mlp_only_layers is None else mlp_only_layers
|
self.mlp_only_layers = [] if mlp_only_layers is None else mlp_only_layers
|
||||||
self.load_balance_coeff = load_balance_coeff
|
self.load_balance_coeff = load_balance_coeff
|
||||||
self.use_grouped_mm = use_grouped_mm
|
self.use_grouped_mm = use_grouped_mm
|
||||||
|
|
||||||
super().__init__(
|
super().__init__(
|
||||||
tie_word_embeddings=tie_word_embeddings,
|
tie_word_embeddings=tie_word_embeddings,
|
||||||
**kwargs,
|
**kwargs,
|
||||||
|
|||||||
@@ -80,4 +80,3 @@ def setup_monitor(
|
|||||||
_MONITOR = MultiMonitor(monitors)
|
_MONITOR = MultiMonitor(monitors)
|
||||||
|
|
||||||
return _MONITOR
|
return _MONITOR
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import verifiers as vf
|
|||||||
|
|
||||||
class Monitor(ABC):
|
class Monitor(ABC):
|
||||||
"""Base class for all monitoring implementations.
|
"""Base class for all monitoring implementations.
|
||||||
|
|
||||||
Subclasses should initialize a `history` attribute as a list of dictionaries
|
Subclasses should initialize a `history` attribute as a list of dictionaries
|
||||||
to store logged metrics.
|
to store logged metrics.
|
||||||
"""
|
"""
|
||||||
@@ -56,4 +56,3 @@ class NoOpMonitor(Monitor):
|
|||||||
|
|
||||||
def log_distributions(self, distributions: dict[str, list[float]], step: int) -> None:
|
def log_distributions(self, distributions: dict[str, list[float]], step: int) -> None:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ from transformers.utils import logging
|
|||||||
|
|
||||||
logger = logging.get_logger(__name__)
|
logger = logging.get_logger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class AfmoeConfig(PretrainedConfig):
|
class AfmoeConfig(PretrainedConfig):
|
||||||
"""
|
"""
|
||||||
n_group (`int`, *optional*, defaults to 1):
|
n_group (`int`, *optional*, defaults to 1):
|
||||||
@@ -25,6 +26,7 @@ class AfmoeConfig(PretrainedConfig):
|
|||||||
topk_group (`int`, *optional*, defaults to 1):
|
topk_group (`int`, *optional*, defaults to 1):
|
||||||
Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
|
Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
model_type = "afmoe"
|
model_type = "afmoe"
|
||||||
base_model_pp_plan = {
|
base_model_pp_plan = {
|
||||||
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
||||||
@@ -84,8 +86,7 @@ class AfmoeConfig(PretrainedConfig):
|
|||||||
self.use_cache = use_cache
|
self.use_cache = use_cache
|
||||||
self.rope_theta = rope_theta
|
self.rope_theta = rope_theta
|
||||||
self.rope_scaling = rope_scaling
|
self.rope_scaling = rope_scaling
|
||||||
|
|
||||||
|
|
||||||
# MoE specific
|
# MoE specific
|
||||||
self.moe_intermediate_size = moe_intermediate_size
|
self.moe_intermediate_size = moe_intermediate_size
|
||||||
self.num_experts_per_tok = num_experts_per_tok
|
self.num_experts_per_tok = num_experts_per_tok
|
||||||
@@ -101,7 +102,6 @@ class AfmoeConfig(PretrainedConfig):
|
|||||||
self.load_balance_coeff = load_balance_coeff
|
self.load_balance_coeff = load_balance_coeff
|
||||||
self.use_grouped_mm = use_grouped_mm
|
self.use_grouped_mm = use_grouped_mm
|
||||||
|
|
||||||
|
|
||||||
# Attention specific
|
# Attention specific
|
||||||
self.attention_dropout = attention_dropout
|
self.attention_dropout = attention_dropout
|
||||||
self.global_attn_every_n_layers = global_attn_every_n_layers
|
self.global_attn_every_n_layers = global_attn_every_n_layers
|
||||||
@@ -109,7 +109,8 @@ class AfmoeConfig(PretrainedConfig):
|
|||||||
self.layer_types = layer_types
|
self.layer_types = layer_types
|
||||||
if self.layer_types is None:
|
if self.layer_types is None:
|
||||||
self.layer_types = [
|
self.layer_types = [
|
||||||
"sliding_attention" if bool((i + 1) % global_attn_every_n_layers) else "full_attention" for i in range(self.num_hidden_layers)
|
"sliding_attention" if bool((i + 1) % global_attn_every_n_layers) else "full_attention"
|
||||||
|
for i in range(self.num_hidden_layers)
|
||||||
]
|
]
|
||||||
layer_type_validation(self.layer_types)
|
layer_type_validation(self.layer_types)
|
||||||
|
|
||||||
@@ -121,7 +122,6 @@ class AfmoeConfig(PretrainedConfig):
|
|||||||
|
|
||||||
self.num_key_value_heads = num_key_value_heads
|
self.num_key_value_heads = num_key_value_heads
|
||||||
|
|
||||||
|
|
||||||
# Validate rope configs
|
# Validate rope configs
|
||||||
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
||||||
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
||||||
|
|||||||
@@ -26,8 +26,8 @@ try:
|
|||||||
except:
|
except:
|
||||||
from configuration_afmoe import AfmoeConfig
|
from configuration_afmoe import AfmoeConfig
|
||||||
|
|
||||||
class AfmoeRotaryEmbedding(nn.Module):
|
|
||||||
|
|
||||||
|
class AfmoeRotaryEmbedding(nn.Module):
|
||||||
def __init__(self, config: AfmoeConfig, device=None):
|
def __init__(self, config: AfmoeConfig, device=None):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
# BC: "rope_type" was originally "type"
|
# BC: "rope_type" was originally "type"
|
||||||
@@ -129,11 +129,10 @@ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
|||||||
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
||||||
if n_rep == 1:
|
if n_rep == 1:
|
||||||
return hidden_states
|
return hidden_states
|
||||||
hidden_states = hidden_states[:, :, None, :, :].expand(
|
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
||||||
batch, num_key_value_heads, n_rep, slen, head_dim
|
|
||||||
)
|
|
||||||
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
||||||
|
|
||||||
|
|
||||||
@use_kernel_forward_from_hub("RMSNorm")
|
@use_kernel_forward_from_hub("RMSNorm")
|
||||||
class AfmoeRMSNorm(nn.Module):
|
class AfmoeRMSNorm(nn.Module):
|
||||||
def __init__(self, hidden_size: int, eps: float):
|
def __init__(self, hidden_size: int, eps: float):
|
||||||
@@ -155,7 +154,6 @@ class AfmoeRMSNorm(nn.Module):
|
|||||||
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def eager_attention_forward(
|
def eager_attention_forward(
|
||||||
module: nn.Module,
|
module: nn.Module,
|
||||||
query: torch.Tensor,
|
query: torch.Tensor,
|
||||||
@@ -174,12 +172,8 @@ def eager_attention_forward(
|
|||||||
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
||||||
attn_weights = attn_weights + causal_mask
|
attn_weights = attn_weights + causal_mask
|
||||||
|
|
||||||
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(
|
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
||||||
query.dtype
|
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
||||||
)
|
|
||||||
attn_weights = nn.functional.dropout(
|
|
||||||
attn_weights, p=dropout, training=module.training
|
|
||||||
)
|
|
||||||
attn_output = torch.matmul(attn_weights, value_states)
|
attn_output = torch.matmul(attn_weights, value_states)
|
||||||
attn_output = attn_output.transpose(1, 2).contiguous()
|
attn_output = attn_output.transpose(1, 2).contiguous()
|
||||||
|
|
||||||
@@ -212,7 +206,7 @@ class AfmoeTokenChoiceRouter(nn.Module):
|
|||||||
self.score_func = config.score_func
|
self.score_func = config.score_func
|
||||||
self.route_norm = config.route_norm
|
self.route_norm = config.route_norm
|
||||||
self.route_scale = config.route_scale
|
self.route_scale = config.route_scale
|
||||||
self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
|
self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)
|
||||||
|
|
||||||
def forward(self, hidden_states, expert_bias: torch.Tensor | None):
|
def forward(self, hidden_states, expert_bias: torch.Tensor | None):
|
||||||
_, _, hidden_dim = hidden_states.shape
|
_, _, hidden_dim = hidden_states.shape
|
||||||
@@ -240,6 +234,7 @@ class AfmoeTokenChoiceRouter(nn.Module):
|
|||||||
top_scores = top_scores * self.route_scale
|
top_scores = top_scores * self.route_scale
|
||||||
return top_scores, selected_experts
|
return top_scores, selected_experts
|
||||||
|
|
||||||
|
|
||||||
class AfmoeMoE(nn.Module):
|
class AfmoeMoE(nn.Module):
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
@@ -248,16 +243,11 @@ class AfmoeMoE(nn.Module):
|
|||||||
|
|
||||||
self.shared_experts = None
|
self.shared_experts = None
|
||||||
if config.num_shared_experts > 0:
|
if config.num_shared_experts > 0:
|
||||||
self.shared_experts = AfmoeMLP(
|
self.shared_experts = AfmoeMLP(config, config.moe_intermediate_size * config.num_shared_experts)
|
||||||
config, config.moe_intermediate_size * config.num_shared_experts
|
|
||||||
)
|
|
||||||
self.experts = nn.ModuleList(
|
self.experts = nn.ModuleList(
|
||||||
[AfmoeMLP(
|
[AfmoeMLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(config.num_experts)]
|
||||||
config, intermediate_size=config.moe_intermediate_size
|
|
||||||
) for _ in range(config.num_experts)]
|
|
||||||
)
|
)
|
||||||
self.expert_bias = nn.Parameter(torch.zeros(config.num_experts, dtype=torch.float32), requires_grad=False)
|
self.expert_bias = nn.Parameter(torch.zeros(config.num_experts, dtype=torch.float32), requires_grad=False)
|
||||||
|
|
||||||
|
|
||||||
def forward(self, hidden_states):
|
def forward(self, hidden_states):
|
||||||
batch_size, seq_len, hidden_dim = hidden_states.shape
|
batch_size, seq_len, hidden_dim = hidden_states.shape
|
||||||
@@ -279,12 +269,8 @@ class AfmoeMoE(nn.Module):
|
|||||||
token_indices_sorted = token_indices_sorted // self.config.num_experts_per_tok
|
token_indices_sorted = token_indices_sorted // self.config.num_experts_per_tok
|
||||||
|
|
||||||
# Gather input tokens
|
# Gather input tokens
|
||||||
token_indices_expanded = token_indices_sorted.unsqueeze(-1).expand(
|
token_indices_expanded = token_indices_sorted.unsqueeze(-1).expand(-1, hidden_dim)
|
||||||
-1, hidden_dim
|
routed_input = torch.gather(hidden_states_flat, dim=0, index=token_indices_expanded)
|
||||||
)
|
|
||||||
routed_input = torch.gather(
|
|
||||||
hidden_states_flat, dim=0, index=token_indices_expanded
|
|
||||||
)
|
|
||||||
|
|
||||||
routed_output = torch.zeros_like(routed_input)
|
routed_output = torch.zeros_like(routed_input)
|
||||||
for expert_id in range(self.config.num_experts):
|
for expert_id in range(self.config.num_experts):
|
||||||
@@ -293,15 +279,11 @@ class AfmoeMoE(nn.Module):
|
|||||||
expert_input = routed_input[mask]
|
expert_input = routed_input[mask]
|
||||||
expert_out = self.experts[expert_id](expert_input)
|
expert_out = self.experts[expert_id](expert_input)
|
||||||
routed_output[mask] = expert_out
|
routed_output[mask] = expert_out
|
||||||
|
|
||||||
routed_output = (
|
routed_output = (routed_output.to(torch.float32) * top_scores_sorted.unsqueeze(-1)).to(hidden_states.dtype)
|
||||||
routed_output.to(torch.float32) * top_scores_sorted.unsqueeze(-1)
|
|
||||||
).to(hidden_states.dtype)
|
|
||||||
|
|
||||||
# Scatter back to original positions
|
# Scatter back to original positions
|
||||||
output = shared_output.scatter_add(
|
output = shared_output.scatter_add(dim=0, index=token_indices_expanded, src=routed_output)
|
||||||
dim=0, index=token_indices_expanded, src=routed_output
|
|
||||||
)
|
|
||||||
|
|
||||||
return output.view(batch_size, seq_len, hidden_dim)
|
return output.view(batch_size, seq_len, hidden_dim)
|
||||||
|
|
||||||
@@ -323,25 +305,15 @@ class AfmoeAttention(nn.Module):
|
|||||||
self.is_local_attention = config.layer_types[layer_idx] == "sliding_attention"
|
self.is_local_attention = config.layer_types[layer_idx] == "sliding_attention"
|
||||||
self.sliding_window = config.sliding_window if self.is_local_attention else None
|
self.sliding_window = config.sliding_window if self.is_local_attention else None
|
||||||
|
|
||||||
self.q_proj = nn.Linear(
|
self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False)
|
||||||
config.hidden_size, self.num_heads * self.head_dim, bias=False
|
self.k_proj = nn.Linear(config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
||||||
)
|
self.v_proj = nn.Linear(config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
||||||
self.k_proj = nn.Linear(
|
self.o_proj = nn.Linear(self.num_heads * self.head_dim, config.hidden_size, bias=False)
|
||||||
config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
|
|
||||||
)
|
|
||||||
self.v_proj = nn.Linear(
|
|
||||||
config.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
|
|
||||||
)
|
|
||||||
self.o_proj = nn.Linear(
|
|
||||||
self.num_heads * self.head_dim, config.hidden_size, bias=False
|
|
||||||
)
|
|
||||||
|
|
||||||
self.q_norm = AfmoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
self.q_norm = AfmoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
||||||
self.k_norm = AfmoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
self.k_norm = AfmoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
||||||
|
|
||||||
self.gate_proj = nn.Linear(
|
self.gate_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False)
|
||||||
config.hidden_size, self.num_heads * self.head_dim, bias=False
|
|
||||||
)
|
|
||||||
|
|
||||||
def forward(
|
def forward(
|
||||||
self,
|
self,
|
||||||
@@ -351,8 +323,7 @@ class AfmoeAttention(nn.Module):
|
|||||||
past_key_value: Optional[Cache] = None,
|
past_key_value: Optional[Cache] = None,
|
||||||
cache_position: Optional[torch.LongTensor] = None,
|
cache_position: Optional[torch.LongTensor] = None,
|
||||||
**kwargs: Unpack[TransformersKwargs],
|
**kwargs: Unpack[TransformersKwargs],
|
||||||
) -> torch.Tensor:
|
) -> torch.Tensor:
|
||||||
|
|
||||||
input_shape = hidden_states.shape[:-1]
|
input_shape = hidden_states.shape[:-1]
|
||||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||||
|
|
||||||
@@ -363,7 +334,7 @@ class AfmoeAttention(nn.Module):
|
|||||||
|
|
||||||
query_states = self.q_norm(query_states)
|
query_states = self.q_norm(query_states)
|
||||||
key_states = self.k_norm(key_states)
|
key_states = self.k_norm(key_states)
|
||||||
|
|
||||||
query_states = query_states.transpose(1, 2)
|
query_states = query_states.transpose(1, 2)
|
||||||
key_states = key_states.transpose(1, 2)
|
key_states = key_states.transpose(1, 2)
|
||||||
value_states = value_states.transpose(1, 2)
|
value_states = value_states.transpose(1, 2)
|
||||||
@@ -378,9 +349,7 @@ class AfmoeAttention(nn.Module):
|
|||||||
|
|
||||||
attention_interface: Callable = eager_attention_forward
|
attention_interface: Callable = eager_attention_forward
|
||||||
if self.config._attn_implementation != "eager":
|
if self.config._attn_implementation != "eager":
|
||||||
attention_interface = ALL_ATTENTION_FUNCTIONS[
|
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
||||||
self.config._attn_implementation
|
|
||||||
]
|
|
||||||
|
|
||||||
output, _ = attention_interface(
|
output, _ = attention_interface(
|
||||||
self,
|
self,
|
||||||
@@ -492,14 +461,9 @@ class AfmoeModel(AfmoePreTrainedModel):
|
|||||||
self.padding_idx = config.pad_token_id
|
self.padding_idx = config.pad_token_id
|
||||||
self.vocab_size = config.vocab_size
|
self.vocab_size = config.vocab_size
|
||||||
|
|
||||||
self.embed_tokens = nn.Embedding(
|
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
||||||
config.vocab_size, config.hidden_size, self.padding_idx
|
|
||||||
)
|
|
||||||
self.layers = nn.ModuleList(
|
self.layers = nn.ModuleList(
|
||||||
[
|
[AfmoeDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
||||||
AfmoeDecoderLayer(config, layer_idx)
|
|
||||||
for layer_idx in range(config.num_hidden_layers)
|
|
||||||
]
|
|
||||||
)
|
)
|
||||||
self.norm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
self.norm = AfmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
||||||
self.rotary_emb = AfmoeRotaryEmbedding(config=config)
|
self.rotary_emb = AfmoeRotaryEmbedding(config=config)
|
||||||
@@ -513,7 +477,6 @@ class AfmoeModel(AfmoePreTrainedModel):
|
|||||||
def set_input_embeddings(self, value):
|
def set_input_embeddings(self, value):
|
||||||
self.embed_tokens = value
|
self.embed_tokens = value
|
||||||
|
|
||||||
|
|
||||||
def forward(
|
def forward(
|
||||||
self,
|
self,
|
||||||
input_ids: torch.LongTensor,
|
input_ids: torch.LongTensor,
|
||||||
@@ -526,9 +489,7 @@ class AfmoeModel(AfmoePreTrainedModel):
|
|||||||
**kwargs: Unpack[TransformersKwargs],
|
**kwargs: Unpack[TransformersKwargs],
|
||||||
) -> MoeModelOutputWithPast:
|
) -> MoeModelOutputWithPast:
|
||||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||||
raise ValueError(
|
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||||
"You must specify exactly one of input_ids or inputs_embeds"
|
|
||||||
)
|
|
||||||
|
|
||||||
if use_cache and past_key_values is None:
|
if use_cache and past_key_values is None:
|
||||||
past_key_values = DynamicCache()
|
past_key_values = DynamicCache()
|
||||||
@@ -537,9 +498,7 @@ class AfmoeModel(AfmoePreTrainedModel):
|
|||||||
inputs_embeds = self.embed_tokens(input_ids)
|
inputs_embeds = self.embed_tokens(input_ids)
|
||||||
|
|
||||||
if cache_position is None:
|
if cache_position is None:
|
||||||
past_seen_tokens = (
|
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
||||||
past_key_values.get_seq_length() if past_key_values is not None else 0
|
|
||||||
)
|
|
||||||
cache_position = torch.arange(
|
cache_position = torch.arange(
|
||||||
past_seen_tokens,
|
past_seen_tokens,
|
||||||
past_seen_tokens + inputs_embeds.shape[1],
|
past_seen_tokens + inputs_embeds.shape[1],
|
||||||
@@ -648,18 +607,13 @@ class AfmoeForCausalLM(AfmoePreTrainedModel, GenerationMixin):
|
|||||||
|
|
||||||
hidden_states = outputs.last_hidden_state
|
hidden_states = outputs.last_hidden_state
|
||||||
# Only compute necessary logits
|
# Only compute necessary logits
|
||||||
slice_indices = (
|
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
||||||
slice(-logits_to_keep, None)
|
|
||||||
if isinstance(logits_to_keep, int)
|
|
||||||
else logits_to_keep
|
|
||||||
)
|
|
||||||
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
||||||
|
|
||||||
loss = None
|
loss = None
|
||||||
if labels is not None:
|
if labels is not None:
|
||||||
loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
|
loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
return MoeCausalLMOutputWithPast(
|
return MoeCausalLMOutputWithPast(
|
||||||
loss=loss,
|
loss=loss,
|
||||||
logits=logits,
|
logits=logits,
|
||||||
|
|||||||
Reference in New Issue
Block a user