Text Generation
Transformers
Safetensors
English
smartcoder_moe
Mixture of Experts
starcoder2
mixture-of-experts
code
smartcoder
conversational
custom_code
Run this model with HF Jobs
Run Johnblick187/SmartCoderMoE on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/Johnblick187/SmartCoderMoE. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/Johnblick187/SmartCoderMoE on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/Johnblick187/SmartCoderMoE. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/Johnblick187/SmartCoderMoE. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use Johnblick187/SmartCoderMoE with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Johnblick187/SmartCoderMoE with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Johnblick187/SmartCoderMoE", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("Johnblick187/SmartCoderMoE", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Johnblick187/SmartCoderMoE with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Johnblick187/SmartCoderMoE" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Johnblick187/SmartCoderMoE", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/Johnblick187/SmartCoderMoE
- SGLang
How to use Johnblick187/SmartCoderMoE with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "Johnblick187/SmartCoderMoE" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Johnblick187/SmartCoderMoE", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "Johnblick187/SmartCoderMoE" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Johnblick187/SmartCoderMoE", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use Johnblick187/SmartCoderMoE with Docker Model Runner:
docker model run hf.co/Johnblick187/SmartCoderMoE
Update modeling_smartcoder_moe.py
Browse files12348 unmodified lines13141516171819202122232425262728293051 unmodified lines82838485868788899091929394959697989910010110210310416 unmodified lines12112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115210 unmodified lines1631641651661671681691701711721731741751761771781796 unmodified lines1861871881891901911921931941951961971981992002012022032042052062072082092102112121 unmodified line2142152162172182192202212222232242252262272282293 unmodified lines23323423523623723823924024124214 unmodified lines25725825926026126226326426526610 unmodified lines27727827928028128228328428528628728828929029129229329429529629729829930030124 unmodified lines32632732832933033133215 unmodified lines348349350351352353354355356357358359360361362363364365366367368369370371372373"""modeling_smartcoder_moe.pyCustom model class for SmartCoderMoE.8 unmodified linesrouter: [32, 2048] router logits- LayerNorm: weight+bias (input_layernorm, post_attention_layernorm)- Final norm: model.norm.weight/biasNOTE ON THE EXPERT KEYS:The checkpoint stores the batched expert tensors as `experts_fc.weight` /`experts_proj.weight` (i.e. they were saved as a module holding a `.weight`Parameter). The previous version of this file declared them as bare`nn.Parameter` (`experts_fc`, no `.weight`) and tried to paper over the mismatchwith a `_load_from_state_dict` remap hook — which does NOT fire correctly under`from_pretrained`, producing UNEXPECTED `experts_fc.weight` / MISSING`experts_fc`. The fix here is structural: wrap each batched expert tensor in atiny `ExpertWeight` module so its natural state_dict key is `experts_fc.weight`,matching the checkpoint exactly. No load hook required."""import mathimport torch51 unmodified lines# ── RoPE ──────────────────────────────────────────────────────────────────────def rotate_half(x):x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2:]return torch.cat([-x2, x1], dim=-1)def apply_rotary_emb(q, k, cos, sin):return (q * cos) + (rotate_half(q) * sin), \(k * cos) + (rotate_half(k) * sin)class RotaryEmbedding(nn.Module):def __init__(self, dim, max_pos=16384, base=10000.0):super().__init__()inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))# persistent=False: inv_freq is a computed constant, NOT a trained weight.# The checkpoint correctly omits it; marking it non-persistent means it is# not expected in the state_dict, killing the spurious MISSING warning.self.register_buffer("inv_freq", inv_freq, persistent=False)self._cached_len = 0def _build_cache(self, seq_len, device):16 unmodified linesdef __init__(self, hidden_size, eps=1e-5):super().__init__()self.weight = nn.Parameter(torch.ones(hidden_size))self.bias = nn.Parameter(torch.zeros(hidden_size))self.eps = epsdef forward(self, x):return F.layer_norm(x, x.shape[-1:], self.weight, self.bias, self.eps)# ── Expert weight holder ──────────────────────────────────────────────────────class ExpertWeight(nn.Module):"""Thin wrapper so a batched expert tensor registers under the key`<name>.weight`, matching how the checkpoint saved it. The forward indexes`.weight` directly; this module exists purely to produce the right key."""def __init__(self, *shape):super().__init__()self.weight = nn.Parameter(torch.empty(*shape))# ── Attention ─────────────────────────────────────────────────────────────────class SmartCoderAttention(nn.Module):def __init__(self, config: SmartCoderMoEConfig):super().__init__()self.num_heads = config.num_attention_headsself.num_kv_heads = config.num_key_value_headsself.head_dim = config.head_dimself.num_kv_groups = self.num_heads // self.num_kv_headsself.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * config.head_dim, bias=True)10 unmodified linesv = self.v_proj(hidden_states).view(B, T, self.num_kv_heads, self.head_dim).transpose(1, 2)cos, sin = self.rotary_emb(T, hidden_states.device)cos = cos[:, :, :T, : self.head_dim]sin = sin[:, :, :T, : self.head_dim]q, k = apply_rotary_emb(q, k, cos, sin)k = k.repeat_interleave(self.num_kv_groups, dim=1)v = v.repeat_interleave(self.num_kv_groups, dim=1)attn = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)causal = torch.triu(torch.full((T, T), float("-inf"), device=q.device, dtype=q.dtype), diagonal=1)attn = attn + causal.unsqueeze(0).unsqueeze(0)if attention_mask is not None:attn = attn + attention_mask6 unmodified linesclass SmartCoderMoEMLP(nn.Module):def __init__(self, config: SmartCoderMoEConfig):super().__init__()H = config.hidden_sizeDI = config.dense_intermediate_sizeNE = config.num_expertsEI = config.expert_intermediate_sizeself.num_experts = NEself.top_k = config.num_experts_per_tokself.dense_fc = nn.Linear(H, DI, bias=True)self.dense_proj = nn.Linear(DI, H, bias=True)# Wrapped so keys are experts_fc.weight / experts_proj.weight (matches ckpt)self.experts_fc = ExpertWeight(NE, EI, H)self.experts_proj = ExpertWeight(NE, H, EI)self.router = nn.Linear(H, NE, bias=False)def forward(self, x):B, T, H = x.shapedense_out = self.dense_proj(F.gelu(self.dense_fc(x)))router_logits = self.router(x)router_weights = F.softmax(router_logits, dim=-1)top_weights, top_indices = router_weights.topk(self.top_k, dim=-1)top_weights = top_weights / top_weights.sum(dim=-1, keepdim=True)1 unmodified lineexpert_out = torch.zeros_like(x)x_flat = x.view(B * T, H)fc_all = self.experts_fc.weight # [NE, EI, H]proj_all = self.experts_proj.weight # [NE, H, EI]for k in range(self.top_k):expert_ids = top_indices[:, :, k].reshape(B * T)weights = top_weights[:, :, k].reshape(B * T, 1)fc_w = fc_all[expert_ids] # [BT, EI, H]proj_w = proj_all[expert_ids] # [BT, H, EI]hidden = F.gelu(torch.bmm(fc_w, x_flat.unsqueeze(-1)).squeeze(-1))out = torch.bmm(proj_w, hidden.unsqueeze(-1)).squeeze(-1)expert_out = expert_out + (out * weights).view(B, T, H)return dense_out + expert_out3 unmodified linesclass SmartCoderDecoderLayer(nn.Module):def __init__(self, config: SmartCoderMoEConfig):super().__init__()self.input_layernorm = LayerNormWithBias(config.hidden_size, config.rms_norm_eps)self.self_attn = SmartCoderAttention(config)self.post_attention_layernorm = LayerNormWithBias(config.hidden_size, config.rms_norm_eps)self.mlp = SmartCoderMoEMLP(config)def forward(self, hidden_states, attention_mask=None, **kwargs):residual = hidden_states14 unmodified linesdef __init__(self, config: SmartCoderMoEConfig):super().__init__()self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)self.layers = nn.ModuleList([SmartCoderDecoderLayer(config) for _ in range(config.num_hidden_layers)])self.norm = LayerNormWithBias(config.hidden_size, config.rms_norm_eps)def forward(self, input_ids, attention_mask=None, **kwargs):hidden_states = self.embed_tokens(input_ids)10 unmodified linesdef __init__(self, config: SmartCoderMoEConfig):super().__init__(config)self.model = SmartCoderMoEModel(config)self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)self.post_init()# No _load_from_state_dict / load_state_dict override needed:# the module structure now produces experts_fc.weight / experts_proj.weight# natively, matching the checkpoint, and inv_freq is non-persistent.def get_input_embeddings(self):return self.model.embed_tokensdef set_input_embeddings(self, value):self.model.embed_tokens = valuedef get_output_embeddings(self):return self.lm_headdef set_output_embeddings(self, new_embeddings):self.lm_head = new_embeddingsdef forward(self,24 unmodified linesreturn {"input_ids": input_ids}# ── Loader (standalone helper) ────────────────────────────────────────────────def load_smartcoder_moe(model_id="Johnblick187/SmartCoderMoE", dtype=torch.bfloat16):import osfrom huggingface_hub import snapshot_download15 unmodified linesfor f in sf_files:state_dict.update(load_file(str(f)))# Keys now match natively (experts_fc.weight / experts_proj.weight) — no remap.missing, unexpected = model.load_state_dict(state_dict, strict=False)# inv_freq is non-persistent so it will show as "missing"; that is expected# and harmless (recomputed at init). Filter it from the report.missing = [m for m in missing if "inv_freq" not in m]if missing:print(f"Missing (unexpected!): {missing[:5]}{'...' if len(missing) > 5 else ''}")else:print("No unexpected missing keys.")if unexpected:print(f"Unexpected: {unexpected[:5]}{'...' if len(unexpected) > 5 else ''}")else:print("No unexpected keys.")model = model.to(dtype)print(f"Loaded! Params: {sum(p.numel() for p in model.parameters()) / 1e9:.2f}B")return model, configfrom transformers import AutoConfig, AutoModelForCausalLMAutoConfig.register("smartcoder_moe", SmartCoderMoEConfig)AutoModelForCausalLM.register(SmartCoderMoEConfig, SmartCoderMoEForCausalLM)12348 unmodified lines1314151617181951 unmodified lines71727374757677787980818283848586878816 unmodified lines10510610710810911011111211311411511611711811912012112212312410 unmodified lines1351361371381391401411421431441451461471481496 unmodified lines1561571581591601611621631641651661671681691701711721731741751761771781791801811 unmodified line1831841851861871881891901911921931941953 unmodified lines19920020120220320420520620720814 unmodified lines22322422522622722822923010 unmodified lines24124224324424524624724824925025125225325425525625725825926024 unmodified lines28528628728828929029115 unmodified lines307308309310311312313314315316317318319320321322323324325326327328329330331332333""modeling_smartcoder_moe.pyCustom model class for SmartCoderMoE.8 unmodified linesrouter: [32, 2048] router logits- LayerNorm: weight+bias (input_layernorm, post_attention_layernorm)- Final norm: model.norm.weight/bias""import mathimport torch51 unmodified lines# ── RoPE ──────────────────────────────────────────────────────────────────────def rotate_half(x):x1, x2 = x[..., :x.shape[-1]//2], x[..., x.shape[-1]//2:]return torch.cat([-x2, x1], dim=-1)def apply_rotary_emb(q, k, cos, sin):return (q * cos) + (rotate_half(q) * sin), \(k * cos) + (rotate_half(k) * sin)class RotaryEmbedding(nn.Module):def __init__(self, dim, max_pos=16384, base=10000.0):super().__init__()inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))self.register_buffer("inv_freq", inv_freq)self._cached_len = 0def _build_cache(self, seq_len, device):16 unmodified linesdef __init__(self, hidden_size, eps=1e-5):super().__init__()self.weight = nn.Parameter(torch.ones(hidden_size))self.bias = nn.Parameter(torch.zeros(hidden_size))self.eps = epsdef forward(self, x):return F.layer_norm(x, x.shape[-1:], self.weight, self.bias, self.eps)# ── Attention ─────────────────────────────────────────────────────────────────class SmartCoderAttention(nn.Module):def __init__(self, config: SmartCoderMoEConfig):super().__init__()self.num_heads = config.num_attention_headsself.num_kv_heads = config.num_key_value_headsself.head_dim = config.head_dimself.num_kv_groups = self.num_heads // self.num_kv_headsself.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * config.head_dim, bias=True)10 unmodified linesv = self.v_proj(hidden_states).view(B, T, self.num_kv_heads, self.head_dim).transpose(1, 2)cos, sin = self.rotary_emb(T, hidden_states.device)cos = cos[:, :, :T, :self.head_dim]sin = sin[:, :, :T, :self.head_dim]q, k = apply_rotary_emb(q, k, cos, sin)k = k.repeat_interleave(self.num_kv_groups, dim=1)v = v.repeat_interleave(self.num_kv_groups, dim=1)attn = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)causal = torch.triu(torch.full((T, T), float("-inf"), device=q.device, dtype=q.dtype), diagonal=1)attn = attn + causal.unsqueeze(0).unsqueeze(0)if attention_mask is not None:attn = attn + attention_mask6 unmodified linesclass SmartCoderMoEMLP(nn.Module):def __init__(self, config: SmartCoderMoEConfig):super().__init__()H = config.hidden_sizeDI = config.dense_intermediate_sizeNE = config.num_expertsEI = config.expert_intermediate_sizeself.num_experts = NEself.top_k = config.num_experts_per_tokself.dense_fc = nn.Linear(H, DI, bias=True)self.dense_proj = nn.Linear(DI, H, bias=True)self.experts_fc = nn.Parameter(torch.empty(NE, EI, H))self.experts_proj = nn.Parameter(torch.empty(NE, H, EI))self.router = nn.Linear(H, NE, bias=False)def forward(self, x):B, T, H = x.shapedense_out = self.dense_proj(F.gelu(self.dense_fc(x)))router_logits = self.router(x)router_weights = F.softmax(router_logits, dim=-1)top_weights, top_indices = router_weights.topk(self.top_k, dim=-1)top_weights = top_weights / top_weights.sum(dim=-1, keepdim=True)1 unmodified lineexpert_out = torch.zeros_like(x)x_flat = x.view(B * T, H)for k in range(self.top_k):expert_ids = top_indices[:, :, k].reshape(B * T)weights = top_weights[:, :, k].reshape(B * T, 1)fc_w = self.experts_fc[expert_ids]proj_w = self.experts_proj[expert_ids]hidden = F.gelu(torch.bmm(fc_w, x_flat.unsqueeze(-1)).squeeze(-1))out = torch.bmm(proj_w, hidden.unsqueeze(-1)).squeeze(-1)expert_out = expert_out + (out * weights).view(B, T, H)return dense_out + expert_out3 unmodified linesclass SmartCoderDecoderLayer(nn.Module):def __init__(self, config: SmartCoderMoEConfig):super().__init__()self.input_layernorm = LayerNormWithBias(config.hidden_size, config.rms_norm_eps)self.self_attn = SmartCoderAttention(config)self.post_attention_layernorm = LayerNormWithBias(config.hidden_size, config.rms_norm_eps)self.mlp = SmartCoderMoEMLP(config)def forward(self, hidden_states, attention_mask=None, **kwargs):residual = hidden_states14 unmodified linesdef __init__(self, config: SmartCoderMoEConfig):super().__init__()self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)self.layers = nn.ModuleList([SmartCoderDecoderLayer(config) for _ in range(config.num_hidden_layers)])self.norm = LayerNormWithBias(config.hidden_size, config.rms_norm_eps)def forward(self, input_ids, attention_mask=None, **kwargs):hidden_states = self.embed_tokens(input_ids)10 unmodified linesdef __init__(self, config: SmartCoderMoEConfig):super().__init__(config)self.model = SmartCoderMoEModel(config)self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)self.post_init()def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs):remapped = {}for k, v in state_dict.items():k = k.replace('experts_fc.weight', 'experts_fc')k = k.replace('experts_proj.weight', 'experts_proj')remapped[k] = vsuper()._load_from_state_dict(remapped, prefix, *args, **kwargs)def get_input_embeddings(self): return self.model.embed_tokensdef get_output_embeddings(self): return self.lm_headdef forward(self,24 unmodified linesreturn {"input_ids": input_ids}# ── Loader ────────────────────────────────────────────────────────────────────def load_smartcoder_moe(model_id="Johnblick187/SmartCoderMoE", dtype=torch.bfloat16):import osfrom huggingface_hub import snapshot_download15 unmodified linesfor f in sf_files:state_dict.update(load_file(str(f)))# Remap expert keys — safetensors has .weight suffix, our params don'tremapped = {}for k, v in state_dict.items():if 'experts_fc.weight' in k:remapped[k.replace('experts_fc.weight', 'experts_fc')] = velif 'experts_proj.weight' in k:remapped[k.replace('experts_proj.weight', 'experts_proj')] = velse:remapped[k] = vstate_dict = remappedmissing, unexpected = model.load_state_dict(state_dict, strict=False)if missing:print(f"Missing: {missing[:3]}{'...' if len(missing)>3 else ''}")if unexpected:print(f"Unexpected: {unexpected[:3]}{'...' if len(unexpected)>3 else ''}")model = model.to(dtype)print(f"Loaded! Params: {sum(p.numel() for p in model.parameters())/1e9:.2f}B")return model, configfrom transformers import AutoConfig, AutoModelForCausalLMAutoConfig.register("smartcoder_moe", SmartCoderMoEConfig)AutoModelForCausalLM.register(SmartCoderMoEConfig, SmartCoderMoEForCausalLM)
modeling_smartcoder_moe.py+52-92