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
|
||||
- name: Run ruff
|
||||
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:
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
# Ruff version.
|
||||
rev: v0.9.3
|
||||
rev: v0.13.0
|
||||
hooks:
|
||||
# Run the linter.
|
||||
- id: ruff
|
||||
- id: ruff-check
|
||||
args: [ --fix, --config=pyproject.toml ]
|
||||
# Run the formatter.
|
||||
- id: ruff-format
|
||||
|
||||
@@ -650,9 +650,7 @@ class OrchestratorConfig(BaseSettings):
|
||||
# Whether to reset inference weights to base model when starting from scratch
|
||||
reload_weights_on_start: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to reset inference weights to the base model when starting from scratch."
|
||||
),
|
||||
Field(description="Whether to reset inference weights to the base model when starting from scratch."),
|
||||
] = True
|
||||
|
||||
# The validation configuration
|
||||
|
||||
@@ -196,7 +196,9 @@ class Scheduler:
|
||||
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")
|
||||
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(
|
||||
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
|
||||
prefix_tokens = tokens["prompt_ids"] + tokens["completion_ids"]
|
||||
|
||||
|
||||
return [interleaved_rollout]
|
||||
|
||||
|
||||
|
||||
@@ -324,7 +324,6 @@ class RLConfig(BaseSettings):
|
||||
batch_size=self.orchestrator.batch_size,
|
||||
)
|
||||
|
||||
|
||||
trainer_bench_enabled = self.trainer.bench is not None
|
||||
if trainer_bench_enabled != self.orchestrator.bench:
|
||||
raise ValueError(
|
||||
|
||||
@@ -33,13 +33,7 @@ def prepare_sample(
|
||||
if teacher_logprobs is not None:
|
||||
teacher_logprobs = teacher_logprobs[:seq_len]
|
||||
|
||||
assert (
|
||||
len(input_ids)
|
||||
== len(advantages)
|
||||
== len(loss_mask)
|
||||
== len(position_ids)
|
||||
== len(inference_logprobs)
|
||||
), (
|
||||
assert 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)}"
|
||||
)
|
||||
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
|
||||
|
||||
|
||||
__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",
|
||||
"AfmoePreTrainedModel",
|
||||
]
|
||||
|
||||
|
||||
@@ -4,8 +4,10 @@ from transformers.utils import logging
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
|
||||
class AfmoeConfig(PretrainedConfig):
|
||||
"""Configuration for AFMoE."""
|
||||
|
||||
model_type = "afmoe"
|
||||
base_model_pp_plan = {
|
||||
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
||||
@@ -88,7 +90,8 @@ class AfmoeConfig(PretrainedConfig):
|
||||
self.layer_types = layer_types
|
||||
if self.layer_types is None:
|
||||
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)
|
||||
|
||||
|
||||
@@ -80,4 +80,3 @@ def setup_monitor(
|
||||
_MONITOR = MultiMonitor(monitors)
|
||||
|
||||
return _MONITOR
|
||||
|
||||
|
||||
@@ -56,4 +56,3 @@ class NoOpMonitor(Monitor):
|
||||
|
||||
def log_distributions(self, distributions: dict[str, list[float]], step: int) -> None:
|
||||
pass
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ from transformers.utils import logging
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
|
||||
class AfmoeConfig(PretrainedConfig):
|
||||
"""
|
||||
n_group (`int`, *optional*, defaults to 1):
|
||||
@@ -25,6 +26,7 @@ class AfmoeConfig(PretrainedConfig):
|
||||
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).
|
||||
"""
|
||||
|
||||
model_type = "afmoe"
|
||||
base_model_pp_plan = {
|
||||
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
||||
@@ -85,7 +87,6 @@ class AfmoeConfig(PretrainedConfig):
|
||||
self.rope_theta = rope_theta
|
||||
self.rope_scaling = rope_scaling
|
||||
|
||||
|
||||
# MoE specific
|
||||
self.moe_intermediate_size = moe_intermediate_size
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
@@ -101,7 +102,6 @@ class AfmoeConfig(PretrainedConfig):
|
||||
self.load_balance_coeff = load_balance_coeff
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
|
||||
|
||||
# Attention specific
|
||||
self.attention_dropout = attention_dropout
|
||||
self.global_attn_every_n_layers = global_attn_every_n_layers
|
||||
@@ -109,7 +109,8 @@ class AfmoeConfig(PretrainedConfig):
|
||||
self.layer_types = layer_types
|
||||
if self.layer_types is None:
|
||||
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)
|
||||
|
||||
@@ -121,7 +122,6 @@ class AfmoeConfig(PretrainedConfig):
|
||||
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
|
||||
|
||||
# Validate rope configs
|
||||
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
||||
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
||||
|
||||
@@ -26,8 +26,8 @@ try:
|
||||
except:
|
||||
from configuration_afmoe import AfmoeConfig
|
||||
|
||||
class AfmoeRotaryEmbedding(nn.Module):
|
||||
|
||||
class AfmoeRotaryEmbedding(nn.Module):
|
||||
def __init__(self, config: AfmoeConfig, device=None):
|
||||
super().__init__()
|
||||
# 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
|
||||
if n_rep == 1:
|
||||
return hidden_states
|
||||
hidden_states = hidden_states[:, :, None, :, :].expand(
|
||||
batch, num_key_value_heads, n_rep, slen, head_dim
|
||||
)
|
||||
hidden_states = hidden_states[:, :, None, :, :].expand(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")
|
||||
class AfmoeRMSNorm(nn.Module):
|
||||
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}"
|
||||
|
||||
|
||||
|
||||
def eager_attention_forward(
|
||||
module: nn.Module,
|
||||
query: torch.Tensor,
|
||||
@@ -174,12 +172,8 @@ def eager_attention_forward(
|
||||
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
||||
attn_weights = attn_weights + causal_mask
|
||||
|
||||
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(
|
||||
query.dtype
|
||||
)
|
||||
attn_weights = nn.functional.dropout(
|
||||
attn_weights, p=dropout, training=module.training
|
||||
)
|
||||
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
||||
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
||||
attn_output = torch.matmul(attn_weights, value_states)
|
||||
attn_output = attn_output.transpose(1, 2).contiguous()
|
||||
|
||||
@@ -240,6 +234,7 @@ class AfmoeTokenChoiceRouter(nn.Module):
|
||||
top_scores = top_scores * self.route_scale
|
||||
return top_scores, selected_experts
|
||||
|
||||
|
||||
class AfmoeMoE(nn.Module):
|
||||
def __init__(self, config):
|
||||
super().__init__()
|
||||
@@ -248,17 +243,12 @@ class AfmoeMoE(nn.Module):
|
||||
|
||||
self.shared_experts = None
|
||||
if config.num_shared_experts > 0:
|
||||
self.shared_experts = AfmoeMLP(
|
||||
config, config.moe_intermediate_size * config.num_shared_experts
|
||||
)
|
||||
self.shared_experts = AfmoeMLP(config, config.moe_intermediate_size * config.num_shared_experts)
|
||||
self.experts = nn.ModuleList(
|
||||
[AfmoeMLP(
|
||||
config, intermediate_size=config.moe_intermediate_size
|
||||
) for _ in range(config.num_experts)]
|
||||
[AfmoeMLP(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)
|
||||
|
||||
|
||||
def forward(self, hidden_states):
|
||||
batch_size, seq_len, hidden_dim = hidden_states.shape
|
||||
hidden_states_flat = hidden_states.view(-1, hidden_dim)
|
||||
@@ -279,12 +269,8 @@ class AfmoeMoE(nn.Module):
|
||||
token_indices_sorted = token_indices_sorted // self.config.num_experts_per_tok
|
||||
|
||||
# Gather input tokens
|
||||
token_indices_expanded = token_indices_sorted.unsqueeze(-1).expand(
|
||||
-1, hidden_dim
|
||||
)
|
||||
routed_input = torch.gather(
|
||||
hidden_states_flat, dim=0, index=token_indices_expanded
|
||||
)
|
||||
token_indices_expanded = token_indices_sorted.unsqueeze(-1).expand(-1, hidden_dim)
|
||||
routed_input = torch.gather(hidden_states_flat, dim=0, index=token_indices_expanded)
|
||||
|
||||
routed_output = torch.zeros_like(routed_input)
|
||||
for expert_id in range(self.config.num_experts):
|
||||
@@ -294,14 +280,10 @@ class AfmoeMoE(nn.Module):
|
||||
expert_out = self.experts[expert_id](expert_input)
|
||||
routed_output[mask] = expert_out
|
||||
|
||||
routed_output = (
|
||||
routed_output.to(torch.float32) * top_scores_sorted.unsqueeze(-1)
|
||||
).to(hidden_states.dtype)
|
||||
routed_output = (routed_output.to(torch.float32) * top_scores_sorted.unsqueeze(-1)).to(hidden_states.dtype)
|
||||
|
||||
# Scatter back to original positions
|
||||
output = shared_output.scatter_add(
|
||||
dim=0, index=token_indices_expanded, src=routed_output
|
||||
)
|
||||
output = shared_output.scatter_add(dim=0, index=token_indices_expanded, src=routed_output)
|
||||
|
||||
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.sliding_window = config.sliding_window if self.is_local_attention else None
|
||||
|
||||
self.q_proj = nn.Linear(
|
||||
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.o_proj = nn.Linear(
|
||||
self.num_heads * self.head_dim, config.hidden_size, bias=False
|
||||
)
|
||||
self.q_proj = nn.Linear(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.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.k_norm = AfmoeRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
||||
|
||||
self.gate_proj = nn.Linear(
|
||||
config.hidden_size, self.num_heads * self.head_dim, bias=False
|
||||
)
|
||||
self.gate_proj = nn.Linear(config.hidden_size, self.num_heads * self.head_dim, bias=False)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
@@ -352,7 +324,6 @@ class AfmoeAttention(nn.Module):
|
||||
cache_position: Optional[torch.LongTensor] = None,
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> torch.Tensor:
|
||||
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
hidden_shape = (*input_shape, -1, self.head_dim)
|
||||
|
||||
@@ -378,9 +349,7 @@ class AfmoeAttention(nn.Module):
|
||||
|
||||
attention_interface: Callable = eager_attention_forward
|
||||
if self.config._attn_implementation != "eager":
|
||||
attention_interface = ALL_ATTENTION_FUNCTIONS[
|
||||
self.config._attn_implementation
|
||||
]
|
||||
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
||||
|
||||
output, _ = attention_interface(
|
||||
self,
|
||||
@@ -492,14 +461,9 @@ class AfmoeModel(AfmoePreTrainedModel):
|
||||
self.padding_idx = config.pad_token_id
|
||||
self.vocab_size = config.vocab_size
|
||||
|
||||
self.embed_tokens = nn.Embedding(
|
||||
config.vocab_size, config.hidden_size, self.padding_idx
|
||||
)
|
||||
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
||||
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.rotary_emb = AfmoeRotaryEmbedding(config=config)
|
||||
@@ -513,7 +477,6 @@ class AfmoeModel(AfmoePreTrainedModel):
|
||||
def set_input_embeddings(self, value):
|
||||
self.embed_tokens = value
|
||||
|
||||
|
||||
def forward(
|
||||
self,
|
||||
input_ids: torch.LongTensor,
|
||||
@@ -526,9 +489,7 @@ class AfmoeModel(AfmoePreTrainedModel):
|
||||
**kwargs: Unpack[TransformersKwargs],
|
||||
) -> MoeModelOutputWithPast:
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError(
|
||||
"You must specify exactly one of input_ids or inputs_embeds"
|
||||
)
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
|
||||
if use_cache and past_key_values is None:
|
||||
past_key_values = DynamicCache()
|
||||
@@ -537,9 +498,7 @@ class AfmoeModel(AfmoePreTrainedModel):
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
|
||||
if cache_position is None:
|
||||
past_seen_tokens = (
|
||||
past_key_values.get_seq_length() if past_key_values is not None else 0
|
||||
)
|
||||
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
||||
cache_position = torch.arange(
|
||||
past_seen_tokens,
|
||||
past_seen_tokens + inputs_embeds.shape[1],
|
||||
@@ -648,18 +607,13 @@ class AfmoeForCausalLM(AfmoePreTrainedModel, GenerationMixin):
|
||||
|
||||
hidden_states = outputs.last_hidden_state
|
||||
# Only compute necessary logits
|
||||
slice_indices = (
|
||||
slice(-logits_to_keep, None)
|
||||
if isinstance(logits_to_keep, int)
|
||||
else logits_to_keep
|
||||
)
|
||||
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, :])
|
||||
|
||||
loss = None
|
||||
if labels is not None:
|
||||
loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
|
||||
|
||||
|
||||
return MoeCausalLMOutputWithPast(
|
||||
loss=loss,
|
||||
logits=logits,
|
||||
|
||||
Reference in New Issue
Block a user