Text Generation
GGUF
Safetensors
English
deepseek2
llama.cpp
mixture-of-experts
multi-head-latent-attention
iq4_nl
mark-ai
systems-engineering
custom_code
conversational
Instructions to use miceworks/Mark-SLM-V3-150M with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- llama.cpp
How to use miceworks/Mark-SLM-V3-150M with llama.cpp:
Install (macOS, Linux)
curl -LsSf https://llama.app/install.sh | sh # Start a local OpenAI-compatible server with a web UI: llama serve -hf miceworks/Mark-SLM-V3-150M:IQ4_NL # Run inference directly in the terminal: llama cli -hf miceworks/Mark-SLM-V3-150M:IQ4_NL
Install from WinGet (Windows)
winget install llama.cpp # Start a local OpenAI-compatible server with a web UI: llama serve -hf miceworks/Mark-SLM-V3-150M:IQ4_NL # Run inference directly in the terminal: llama cli -hf miceworks/Mark-SLM-V3-150M:IQ4_NL
Build from source code
git clone https://github.com/ggml-org/llama.cpp.git cd llama.cpp cmake -B build cmake --build build -j --target llama-app # Start a local OpenAI-compatible server with a web UI: ./build/bin/llama serve -hf miceworks/Mark-SLM-V3-150M:IQ4_NL # Run inference directly in the terminal: ./build/bin/llama cli -hf miceworks/Mark-SLM-V3-150M:IQ4_NL
Use Docker
docker model run hf.co/miceworks/Mark-SLM-V3-150M:IQ4_NL
- Llama new
- LM Studio
- Jan
- vLLM
How to use miceworks/Mark-SLM-V3-150M with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "miceworks/Mark-SLM-V3-150M" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "miceworks/Mark-SLM-V3-150M", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/miceworks/Mark-SLM-V3-150M:IQ4_NL
- Ollama
How to use miceworks/Mark-SLM-V3-150M with Ollama:
ollama run hf.co/miceworks/Mark-SLM-V3-150M:IQ4_NL
- Unsloth Desktop
- Docker Model Runner
How to use miceworks/Mark-SLM-V3-150M with Docker Model Runner:
docker model run hf.co/miceworks/Mark-SLM-V3-150M:IQ4_NL
- Lemonade
How to use miceworks/Mark-SLM-V3-150M with Lemonade:
Pull the model
# Download Lemonade from https://lemonade-server.ai/ lemonade pull miceworks/Mark-SLM-V3-150M:IQ4_NL
Run and chat with the model
lemonade run user.Mark-SLM-V3-150M-IQ4_NL
List all available models
lemonade list
- Atomic Chat
restore: revert modeling_mark_v3.py to verified 16.36 baseline checkpoint
Browse files1234567891011121314156 unmodified lines2223242526272829303132335 unmodified lines394041424344454647484950515253547 unmodified lines6263646566676869707172737475767778791 unmodified line818283848586878889909192939495969798991001011021031041051064 unmodified lines1111121131141151162 unmodified lines1191201211221231241251261271281291301311321331341351361371381391401411422 unmodified lines1451461471481491501511522 unmodified lines1551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851 unmodified line187188189190191192193194195196197198199200201202203204205206207208209210211212213import mathfrom typing import Optional, Tupleimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom transformers import PreTrainedModel, GenerationMixinfrom transformers.modeling_outputs import CausalLMOutputWithPasttry:from .configuration_mark_v3 import MarkV3Configexcept ImportError:from configuration_mark_v3 import MarkV3Configclass RMSNorm(nn.Module):def __init__(self, dim: int, eps: float = 1e-6):super().__init__()6 unmodified linesvar = torch.mean(x_f.pow(2), dim=-1, keepdim=True)return (x_f * torch.rsqrt(var + self.eps) * self.weight.float()).to(orig_dtype)class MarkV3RotaryEmbedding(nn.Module):def __init__(self, config: MarkV3Config):super().__init__()self.dim = config.qk_rope_head_dimself.base = config.rope_thetaself.scale = config.rope_scaling_factorinv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float() / self.dim))inv_freq = inv_freq / self.scaleself.register_buffer("inv_freq", inv_freq, persistent=False)5 unmodified linesemb = torch.cat((freqs, freqs), dim=-1)return emb.cos(), emb.sin()def rotate_half(x: torch.Tensor) -> torch.Tensor:x1 = x[..., : x.shape[-1] // 2]x2 = x[..., x.shape[-1] // 2 :]return torch.cat((-x2, x1), dim=-1)def apply_rotary_pos_emb(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:seqlen = x.shape[2]cos = cos[:seqlen].unsqueeze(0).unsqueeze(1)sin = sin[:seqlen].unsqueeze(0).unsqueeze(1)return ((x * cos) + (rotate_half(x) * sin)).to(x.dtype)class MarkV3MLA(nn.Module):def __init__(self, config: MarkV3Config, layer_idx: int):7 unmodified linesself.qk_rope_head_dim = config.qk_rope_head_dimself.v_head_dim = config.v_head_dimself.qk_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dimself.wq_a = nn.Linear(self.hidden_size, self.q_lora_rank, bias=False)self.q_norm = RMSNorm(self.q_lora_rank, eps=config.rms_norm_eps)self.wq_b = nn.Linear(self.q_lora_rank, self.n_heads * self.qk_head_dim, bias=False)self.wkv_a = nn.Linear(self.hidden_size, self.kv_lora_rank + self.qk_rope_head_dim, bias=False)self.kv_norm = RMSNorm(self.kv_lora_rank, eps=config.rms_norm_eps)self.wk_b = nn.Linear(self.kv_lora_rank, self.n_heads * self.qk_nope_head_dim, bias=False)self.wv_b = nn.Linear(self.kv_lora_rank, self.n_heads * self.v_head_dim, bias=False)self.wo = nn.Linear(self.n_heads * self.v_head_dim, self.hidden_size, bias=False)self.softmax_scale = 1.0 / math.sqrt(self.qk_head_dim)def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:bsz, seqlen, _ = x.shapeq_comp = self.wq_a(x)q_normed = self.q_norm(q_comp)q = self.wq_b(q_normed).view(bsz, seqlen, self.n_heads, self.qk_head_dim).transpose(1, 2)1 unmodified lineq_rope = q[..., self.qk_nope_head_dim :]q_rope = apply_rotary_pos_emb(q_rope, cos, sin)q = torch.cat([q_nope, q_rope], dim=-1)kv_comp = self.wkv_a(x)c_kv = kv_comp[..., : self.kv_lora_rank]k_rope = kv_comp[..., self.kv_lora_rank :]c_kv_normed = self.kv_norm(c_kv)k_nope = self.wk_b(c_kv_normed).view(bsz, seqlen, self.n_heads, self.qk_nope_head_dim).transpose(1, 2)v = self.wv_b(c_kv_normed).view(bsz, seqlen, self.n_heads, self.v_head_dim).transpose(1, 2)k_rope = k_rope.view(bsz, seqlen, 1, self.qk_rope_head_dim).transpose(1, 2)k_rope = apply_rotary_pos_emb(k_rope, cos, sin)k_rope = k_rope.expand(-1, self.n_heads, -1, -1)k = torch.cat([k_nope, k_rope], dim=-1)out = F.scaled_dot_product_attention(q, k, v,attn_mask=None,dropout_p=0.0,is_causal=(seqlen > 1),scale=self.softmax_scale,)out = out.transpose(1, 2).contiguous().view(bsz, seqlen, self.n_heads * self.v_head_dim)return self.wo(out)class MarkV3SwiGLU(nn.Module):def __init__(self, hidden_size: int, intermediate_size: int):super().__init__()4 unmodified linesdef forward(self, x: torch.Tensor) -> torch.Tensor:return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x))class MarkV3MoE(nn.Module):def __init__(self, config: MarkV3Config):super().__init__()2 unmodified linesself.n_shared_experts = config.n_shared_expertsself.top_k = config.num_experts_per_tokself.moe_intermediate_size = config.moe_intermediate_sizeself.shared_experts = MarkV3SwiGLU(self.hidden_size, self.moe_intermediate_size * self.n_shared_experts)self.routed_experts = nn.ModuleList([MarkV3SwiGLU(self.hidden_size, self.moe_intermediate_size)for _ in range(self.n_routed_experts)])self.router = nn.Linear(self.hidden_size, self.n_routed_experts, bias=False)self.exp_probs_b = nn.Parameter(torch.zeros(self.n_routed_experts), requires_grad=False)def forward(self, x: torch.Tensor) -> torch.Tensor:bsz, seqlen, dim = x.shapex_flat = x.view(-1, dim)shared_out = self.shared_experts(x_flat)router_logits = self.router(x_flat)p = torch.sigmoid(router_logits.float())s = p + self.exp_probs_b.unsqueeze(0)_, topk_idx = torch.topk(s, k=self.top_k, dim=-1, sorted=False)topk_weights = torch.gather(p, dim=-1, index=topk_idx)topk_weights = (topk_weights / topk_weights.sum(dim=-1, keepdim=True).clamp(min=1e-6)).to(x.dtype)routed_out = torch.zeros_like(x_flat)for e_idx in range(self.n_routed_experts):token_idx, k_idx = torch.where(topk_idx == e_idx)2 unmodified linesw = topk_weights[token_idx, k_idx].unsqueeze(-1)exp_out = (w * self.routed_experts[e_idx](selected)).to(routed_out.dtype)routed_out.index_add_(0, token_idx, exp_out)return (shared_out + routed_out).view(bsz, seqlen, dim)class MarkV3Block(nn.Module):def __init__(self, config: MarkV3Config, layer_idx: int):super().__init__()2 unmodified linesself.ffn_norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)self.ffn = MarkV3MoE(config)def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:h = x + self.attn(self.attn_norm(x), cos, sin)out = h + self.ffn(self.ffn_norm(h))return outclass MarkV3ForCausalLM(PreTrainedModel, GenerationMixin):config_class = MarkV3Config_tied_weights_keys = ["lm_head.weight"]def __init__(self, config: MarkV3Config):super().__init__(config)self.config = configself.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)self.layers = nn.ModuleList([MarkV3Block(config, i) for i in range(config.num_hidden_layers)])self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)self.rotary_emb = MarkV3RotaryEmbedding(config)self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)if config.tie_word_embeddings:self.lm_head.weight = self.embed_tokens.weightdef get_input_embeddings(self):return self.embed_tokensdef set_input_embeddings(self, value):self.embed_tokens = valuedef get_output_embeddings(self):return self.lm_head1 unmodified linedef set_output_embeddings(self, new_embeddings):self.lm_head = new_embeddingsdef prepare_inputs_for_generation(self, input_ids, **kwargs):return {"input_ids": input_ids}def forward(self,input_ids: torch.Tensor,attention_mask: Optional[torch.Tensor] = None,labels: Optional[torch.Tensor] = None,**kwargs,) -> CausalLMOutputWithPast:bsz, seqlen = input_ids.shapex = self.embed_tokens(input_ids)cos, sin = self.rotary_emb(seqlen, device=input_ids.device)for layer in self.layers:x = layer(x, cos, sin)h = self.norm(x)logits = self.lm_head(h)loss = Noneif labels is not None:shift_logits = logits[..., :-1, :].contiguous()shift_labels = labels[..., 1:].contiguous()loss_fct = nn.CrossEntropyLoss()loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))return CausalLMOutputWithPast(loss=loss, logits=logits)1234567891011121314151617181920212223246 unmodified lines3132333435363738394041424344455 unmodified lines51525354555657585960616263646566676869707 unmodified lines787980818283848586878889909192939495969798991001011021031041051061071081 unmodified line1101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611624 unmodified lines1671681691701711721732 unmodified lines1761771781791801811821831841851861871881891901911921931941951961971981992002012022032042 unmodified lines2072082092102112122132142152162 unmodified lines2192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013021 unmodified line304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336"""Hugging Face Transformers Compatible Modeling Implementation for Mark-SLM-V3-150MSparse Mixture-of-Experts (MoE) Architecture with Multi-Head Latent Attention (MLA).Total parameters: 146,899,248 (< 150M)."""import mathfrom typing import Dict, Optional, Tuple, Unionimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom transformers.modeling_outputs import CausalLMOutputWithPastfrom transformers.modeling_utils import PreTrainedModeltry:from .configuration_mark_v3 import MarkV3Configexcept (ImportError, ValueError):from configuration_mark_v3 import MarkV3Configclass RMSNorm(nn.Module):def __init__(self, dim: int, eps: float = 1e-6):super().__init__()6 unmodified linesvar = torch.mean(x_f.pow(2), dim=-1, keepdim=True)return (x_f * torch.rsqrt(var + self.eps) * self.weight.float()).to(orig_dtype)class MarkV3YaRNRotaryEmbedding(nn.Module):def __init__(self, config: MarkV3Config):super().__init__()self.dim = config.qk_rope_head_dimself.max_seq_len = config.max_position_embeddingsself.base = config.rope_thetaself.scale = config.rope_scaling_factorinv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float() / self.dim))inv_freq = inv_freq / self.scaleself.register_buffer("inv_freq", inv_freq, persistent=False)5 unmodified linesemb = torch.cat((freqs, freqs), dim=-1)return emb.cos(), emb.sin()def rotate_half(x: torch.Tensor) -> torch.Tensor:x1 = x[..., : x.shape[-1] // 2]x2 = x[..., x.shape[-1] // 2 :]return torch.cat((-x2, x1), dim=-1)def apply_rotary_pos_emb(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:# x: (bsz, n_heads, seqlen, head_dim)seqlen = x.shape[2]cos = cos[:seqlen].unsqueeze(0).unsqueeze(1) # (1, 1, seqlen, dim)sin = sin[:seqlen].unsqueeze(0).unsqueeze(1)return (x * cos) + (rotate_half(x) * sin)class MarkV3MLA(nn.Module):def __init__(self, config: MarkV3Config, layer_idx: int):7 unmodified linesself.qk_rope_head_dim = config.qk_rope_head_dimself.v_head_dim = config.v_head_dimself.qk_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim# Q LoRA projectionself.wq_a = nn.Linear(self.hidden_size, self.q_lora_rank, bias=False)self.q_norm = RMSNorm(self.q_lora_rank, eps=config.rms_norm_eps)self.wq_b = nn.Linear(self.q_lora_rank, self.n_heads * self.qk_head_dim, bias=False)# KV LoRA projectionself.wkv_a = nn.Linear(self.hidden_size, self.kv_lora_rank + self.qk_rope_head_dim, bias=False)self.kv_norm = RMSNorm(self.kv_lora_rank, eps=config.rms_norm_eps)self.wk_b = nn.Linear(self.kv_lora_rank, self.n_heads * self.qk_nope_head_dim, bias=False)self.wv_b = nn.Linear(self.kv_lora_rank, self.n_heads * self.v_head_dim, bias=False)self.wo = nn.Linear(self.n_heads * self.v_head_dim, self.hidden_size, bias=False)self.softmax_scale = 1.0 / math.sqrt(self.qk_head_dim)def forward(self,x: torch.Tensor,cos: torch.Tensor,sin: torch.Tensor,attention_mask: Optional[torch.Tensor] = None,) -> torch.Tensor:bsz, seqlen, _ = x.shape# Query computationq_comp = self.wq_a(x)q_normed = self.q_norm(q_comp)q = self.wq_b(q_normed).view(bsz, seqlen, self.n_heads, self.qk_head_dim).transpose(1, 2)1 unmodified lineq_rope = q[..., self.qk_nope_head_dim :]q_rope = apply_rotary_pos_emb(q_rope, cos, sin)q = torch.cat([q_nope, q_rope], dim=-1)# Key-Value computationkv_comp = self.wkv_a(x)c_kv = kv_comp[..., : self.kv_lora_rank]k_rope = kv_comp[..., self.kv_lora_rank :]c_kv_normed = self.kv_norm(c_kv)k_nope = self.wk_b(c_kv_normed).view(bsz, seqlen, self.n_heads, self.qk_nope_head_dim).transpose(1, 2)v = self.wv_b(c_kv_normed).view(bsz, seqlen, self.n_heads, self.v_head_dim).transpose(1, 2)k_rope = k_rope.view(bsz, seqlen, 1, self.qk_rope_head_dim).transpose(1, 2)k_rope = apply_rotary_pos_emb(k_rope, cos, sin)k_rope = k_rope.expand(-1, self.n_heads, -1, -1)k = torch.cat([k_nope, k_rope], dim=-1)# Attention maskingif attention_mask is not None:if attention_mask.dim() == 2:causal = torch.triu(torch.full((seqlen, seqlen), float("-inf"), device=x.device, dtype=q.dtype),diagonal=1,)pad_4d = (1.0 - attention_mask[:, None, None, :].to(dtype=q.dtype, device=x.device)) * -1e9attn_mask = causal + pad_4dis_causal = Falseelif attention_mask.dim() == 4:attn_mask = attention_mask.to(dtype=q.dtype, device=x.device)is_causal = Falseelse:attn_mask = attention_mask.to(device=x.device)is_causal = Falseelse:attn_mask = Noneis_causal = seqlen > 1out = F.scaled_dot_product_attention(q, k, v,attn_mask=attn_mask,dropout_p=0.0,is_causal=is_causal,scale=self.softmax_scale,)out = out.transpose(1, 2).contiguous().view(bsz, seqlen, self.n_heads * self.v_head_dim)return self.wo(out)class MarkV3SwiGLU(nn.Module):def __init__(self, hidden_size: int, intermediate_size: int):super().__init__()4 unmodified linesdef forward(self, x: torch.Tensor) -> torch.Tensor:return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x))class MarkV3MoE(nn.Module):def __init__(self, config: MarkV3Config):super().__init__()2 unmodified linesself.n_shared_experts = config.n_shared_expertsself.top_k = config.num_experts_per_tokself.moe_intermediate_size = config.moe_intermediate_sizeself.shared_experts = MarkV3SwiGLU(self.hidden_size, self.moe_intermediate_size * self.n_shared_experts)self.routed_experts = nn.ModuleList([MarkV3SwiGLU(self.hidden_size, self.moe_intermediate_size)for _ in range(self.n_routed_experts)])self.router = nn.Linear(self.hidden_size, self.n_routed_experts, bias=False)self.exp_probs_b = nn.Parameter(torch.zeros(self.n_routed_experts))def forward(self, x: torch.Tensor) -> torch.Tensor:bsz, seqlen, dim = x.shapex_flat = x.view(-1, dim)shared_out = self.shared_experts(x_flat)router_logits = self.router(x_flat)p = torch.sigmoid(router_logits.float())s = p + self.exp_probs_b.unsqueeze(0)_, topk_idx = torch.topk(s, k=self.top_k, dim=-1, sorted=False)topk_weights = torch.gather(p, dim=-1, index=topk_idx)topk_weights = (topk_weights / topk_weights.sum(dim=-1, keepdim=True).clamp(min=1e-6)).to(x.dtype)routed_out = torch.zeros_like(x_flat)for e_idx in range(self.n_routed_experts):token_idx, k_idx = torch.where(topk_idx == e_idx)2 unmodified linesw = topk_weights[token_idx, k_idx].unsqueeze(-1)exp_out = (w * self.routed_experts[e_idx](selected)).to(routed_out.dtype)routed_out.index_add_(0, token_idx, exp_out)return (shared_out + routed_out).view(bsz, seqlen, dim)class MarkV3Block(nn.Module):def __init__(self, config: MarkV3Config, layer_idx: int):super().__init__()2 unmodified linesself.ffn_norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)self.ffn = MarkV3MoE(config)def forward(self,x: torch.Tensor,cos: torch.Tensor,sin: torch.Tensor,attention_mask: Optional[torch.Tensor] = None,) -> torch.Tensor:h = x + self.attn(self.attn_norm(x), cos, sin, attention_mask=attention_mask)out = h + self.ffn(self.ffn_norm(h))return outclass MarkV3PreTrainedModel(PreTrainedModel):config_class = MarkV3Configbase_model_prefix = "model"supports_gradient_checkpointing = Truedef _init_weights(self, module):std = 0.02if isinstance(module, nn.Linear):nn.init.normal_(module.weight, mean=0.0, std=std)if module.bias is not None:nn.init.zeros_(module.bias)elif isinstance(module, nn.Embedding):nn.init.normal_(module.weight, mean=0.0, std=std)if module.padding_idx is not None:module.weight.data[module.padding_idx].zero_()class MarkV3Model(MarkV3PreTrainedModel):def __init__(self, config: MarkV3Config):super().__init__(config)self.config = configself.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)self.layers = nn.ModuleList([MarkV3Block(config, i) for i in range(config.num_hidden_layers)])self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)self.rotary_emb = MarkV3YaRNRotaryEmbedding(config)self.post_init()def forward(self,input_ids: torch.Tensor,attention_mask: Optional[torch.Tensor] = None,) -> torch.Tensor:bsz, seqlen = input_ids.shapex = self.embed_tokens(input_ids)cos, sin = self.rotary_emb(seqlen, device=input_ids.device)for layer in self.layers:x = layer(x, cos, sin, attention_mask=attention_mask)return self.norm(x)class MarkV3ForCausalLM(MarkV3PreTrainedModel):_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}def __init__(self, config: MarkV3Config):super().__init__(config)self.model = MarkV3Model(config)self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)if config.tie_word_embeddings:self.lm_head.weight = self.model.embed_tokens.weighttry:self.post_init()except (AttributeError, TypeError, Exception):self.apply(self._init_weights)self.tie_weights()def tie_weights(self, *args, **kwargs):if getattr(self.config, "tie_word_embeddings", True) and hasattr(self, "model") and hasattr(self.model, "embed_tokens"):self.lm_head.weight = self.model.embed_tokens.weightdef 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_head1 unmodified linedef set_output_embeddings(self, new_embeddings):self.lm_head = new_embeddingsdef forward(self,input_ids: torch.Tensor,attention_mask: Optional[torch.Tensor] = None,labels: Optional[torch.Tensor] = None,return_dict: Optional[bool] = True,**kwargs,) -> Union[CausalLMOutputWithPast, Tuple[torch.Tensor, ...]]:h = self.model(input_ids, attention_mask=attention_mask)logits = self.lm_head(h)loss = Noneif labels is not None:# Shift internally so that tokens < n predict nshift_logits = logits[..., :-1, :].contiguous()shift_labels = labels[..., 1:].contiguous()loss_fct = nn.CrossEntropyLoss()loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))if not return_dict:output = (logits,)return ((loss,) + output) if loss is not None else outputreturn CausalLMOutputWithPast(loss=loss,logits=logits,past_key_values=None,hidden_states=None,attentions=None,)
modeling_mark_v3.py+152-29