Text Generation
Transformers
Safetensors
English
maincoder
feature-extraction
code
python
code-generation
reinforcement-learning
mcpo
conversational
custom_code
Run this model with HF Jobs
Run Maincode/Maincoder-1B 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/Maincode/Maincoder-1B. 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/Maincode/Maincoder-1B 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/Maincode/Maincoder-1B. 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/Maincode/Maincoder-1B. 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 Maincode/Maincoder-1B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Maincode/Maincoder-1B with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Maincode/Maincoder-1B", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("Maincode/Maincoder-1B", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Maincode/Maincoder-1B with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Maincode/Maincoder-1B" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Maincode/Maincoder-1B", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/Maincode/Maincoder-1B
- SGLang
How to use Maincode/Maincoder-1B 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 "Maincode/Maincoder-1B" \ --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": "Maincode/Maincoder-1B", "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 "Maincode/Maincoder-1B" \ --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": "Maincode/Maincoder-1B", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use Maincode/Maincoder-1B with Docker Model Runner:
docker model run hf.co/Maincode/Maincoder-1B
Upload folder using huggingface_hub
Browse filesFiles changed (15)
- .gitattributes+1
- README.mdAdded+189
- __init__.pyAdded+30
- added_tokens.jsonAdded+24
- chat_template.jinjaAdded+54
- config.jsonAdded+34
- configuration_maincoder.pyAdded+141
- generation_config.jsonAdded+11
- merges.txtAdded
- model.safetensorsAdded+3
- modelling_maincoder.pyAdded+487
- special_tokens_map.jsonAdded+31
- tokenizer.jsonAdded+3
- tokenizer_config.jsonAdded+207
- vocab.jsonAdded
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -texttokenizer.json filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189---license: apache-2.0language:- enlibrary_name: transformerstags:- code- python- maincoder- code-generation- reinforcement-learning- mcpopipeline_tag: text-generationbase_model: Maincode/Maincoder-1B---<img src="https://huggingface.co/datasets/Maincode/assets/resolve/e51154e034201be1a5dad0e9c8de31d8b9f17643/maincoder_logo.png" alt="" width="1250">
[**Maincoder-1B**](https://maincode.com/maincoder/) is a code-focused language model optimized for code generation and completion tasks. The model achieves strong performance on coding benchmarks while maintaining a compact size suitable for local deployment.
# Key Features
- **Code Generation**: Optimized for Python code completion and generation tasks.- **Compact Size**: 1 billion parameters, lightweight enough to run on consumer hardware.- **Deep Architecture**: Modern transformer architecture with RoPE embeddings, grouped-query attention, QK normalization and high depth-to-width ratio.- **Advanced Data Mixing**: Pre-trained and mid-trained on custom data mixes developed for high-performance coding.- **MCPO Algorithm**: Fine-tuned with specialised reinforcement learning policy optimisation algorithm to improve training stability and accelerate convergence.- **SOTA Performance**: State-of-the-art performance on Python coding benchmarks HumanEval, HumanEval+ and MBPP+.
# Benchmark Results
<img src="https://huggingface.co/datasets/Maincode/assets/resolve/main/performance_h.png" alt="Benchmark Performance Across Baseline LLMs" width="1050">
| Model | HumanEval | HumanEval+ | MBPP+ | MMLU | GSM8K ||---|---:|---:|---:|---:|---:|| [Maincode/Maincoder-1B](https://huggingface.co/Maincode/Maincoder-1B) | **0.7622** | **0.7256** | **0.7090** | 0.3054 | 0.2976 || [deepseek-ai/deepseek-coder-1.3b-instruct](https://huggingface.co/deepseek-ai/deepseek-coder-1.3b-instruct) | 0.5610 | 0.5305 | 0.6217 | 0.2705 | 0.0413 || [HuggingFaceTB/SmolLM3-3B](https://huggingface.co/HuggingFaceTB/SmolLM3-3B) | 0.5366 | 0.5000 | 0.6799 | **0.5928** | 0.5505 || [Qwen/Qwen2.5-Coder-1.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-Coder-1.5B-Instruct) | 0.4634 | 0.4451 | 0.6561 | 0.4984 | 0.4944 || [Qwen/Qwen3-1.7B](https://huggingface.co/Qwen/Qwen3-1.7B) | 0.4024 | 0.3780 | 0.5582 | 0.5571 |**0.6865** |
# Model Overview
Maincoder uses a modern transformer decoder architecture with:
- **Rotary Position Embeddings**: With theta of 1,000,000.- **RMSNorm**: Pre-normalization for stable training.- **Grouped Query Attention**: 4:1 ratio of query to key-value heads.- **QK Normalization**: RMSNorm applied to attention queries and keys.- **SwiGLU MLP**: Gated linear units with SiLU activation.
| Attribute | Value ||-----------|-------|| Parameters | 1B || Hidden Size | 1536 || Layers | 32 || Attention Heads | 16 (4 KV heads) || Head Dimension | 96 || Vocabulary Size | 151,936 || Context Length | 2,048 || Precision | bfloat16 |
# Usage
### Installation
```bashpip install transformers torch```
### Quick Start
```pythonfrom transformers import AutoModelForCausalLM, AutoTokenizer
model = AutoModelForCausalLM.from_pretrained( "Maincode/Maincoder-1B", torch_dtype="auto", device_map="auto", trust_remote_code=True,)tokenizer = AutoTokenizer.from_pretrained( "Maincode/Maincoder-1B", trust_remote_code=True,)
# Code completion exampleprompt = '''def fibonacci(n: int) -> int: """Return the n-th Fibonacci number."""'''
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)outputs = model.generate( **inputs, max_new_tokens=256, temperature=0.2, do_sample=True,)print(tokenizer.decode(outputs[0], skip_special_tokens=True))```
### Code Completion
```python# Function completionprompt = '''def quicksort(arr: list) -> list: """Sort a list using the quicksort algorithm."""'''
# Class completionprompt = '''class BinarySearchTree: """A binary search tree implementation.""" def __init__(self):'''
# Algorithm implementationprompt = '''def dijkstra(graph: dict, start: str, end: str) -> tuple: """Find the shortest path using Dijkstra's algorithm. Args: graph: Adjacency list representation of the graph start: Starting node end: Target node Returns: Tuple of (distance, path) """'''```
# Additional Notes
## Reproducibility
<details><summary>Model evaluations were run on 8 AMD MI355X GPUs via the <a href="https://github.com/EleutherAI/lm-evaluation-harness">EleutherAI</a> framework.</summary>
```bashdocker run --rm -it \ --device=/dev/kfd --device=/dev/dri --group-add=video \ --ipc=host --security-opt seccomp=unconfined \ -v $(pwd):/workspace -w /workspace \ -e HF_TOKEN \ -e PYTHONHASHSEED=0 \ -e TORCH_DETERMINISTIC=1 \ -e ROCBLAS_ATOMICS_MODE="0" \ -e MIOPEN_FIND_MODE="1" \ -e CUBLAS_WORKSPACE_CONFIG=":4096:8" \ -e HF_ALLOW_CODE_EVAL="1" \ rocm/pytorch:rocm7.1.1_ubuntu24.04_py3.12_pytorch_release_2.9.1 \ bash -c 'pip install "lm_eval[hf]" && \ accelerate launch -m lm_eval \ --model hf --model_args "pretrained=Maincode/Maincoder-1B,trust_remote_code=True,dtype=float32" \ --tasks humaneval,humaneval_plus,mbpp_plus,mmlu,gsm8k \ --device cuda:0 --batch_size 32 --seed 42 \ --confirm_run_unsafe_code'```
</details>
## Limitations
- Context length limited to 2,048 tokens- Primarily optimized for Python, performance may vary on other languages- May generate code with bugs or security issues - always review generated code
<div style="margin-left:14px; border-left:4px solid #3b82f6; background:rgba(59,130,246,0.08); padding:8px 10px; border-radius:8px; font-size:0.92em; margin:10px 0;"> <strong>Disclaimer</strong>: This model has <strong>not</strong> undergone any alignment or safety tuning (e.g., RLHF/RLAIF, DPO, or safety fine-tuning). Outputs may be unsafe or biased. Please use appropriate safeguards and evaluate carefully for your use case.</div>
## License
This model is released under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0).
## Citation
```bibtex@misc{maincoder2025, title = {Maincoder-1B: A High-Performance 1B Parameter Coding Model}, author = {Maincode Team}, year = {2025}, organization = {Maincode}, howpublished = {\url{https://huggingface.co/Maincode/Maincoder-1B}}}```
## Contact
For questions, issues, or collaboration inquiries, please visit [Maincode](https://maincode.com).123456789101112131415161718192021222324252627282930# coding=utf-8# Copyright 2025 Maincode. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
from .configuration_maincoder import MaincoderConfigfrom .modelling_maincoder import ( MaincoderForCausalLM, MaincoderModel, MaincoderPreTrainedModel,)
__all__ = [ "MaincoderConfig", "MaincoderPreTrainedModel", "MaincoderModel", "MaincoderForCausalLM",]
123456789101112131415161718192021222324{ "</tool_call>": 151658, "<tool_call>": 151657, "<|box_end|>": 151649, "<|box_start|>": 151648, "<|endoftext|>": 151643, "<|file_sep|>": 151664, "<|fim_middle|>": 151660, "<|fim_pad|>": 151662, "<|fim_prefix|>": 151659, "<|fim_suffix|>": 151661, "<|im_end|>": 151645, "<|im_start|>": 151644, "<|image_pad|>": 151655, "<|object_ref_end|>": 151647, "<|object_ref_start|>": 151646, "<|quad_end|>": 151651, "<|quad_start|>": 151650, "<|repo_name|>": 151663, "<|video_pad|>": 151656, "<|vision_end|>": 151653, "<|vision_pad|>": 151654, "<|vision_start|>": 151652}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354{%- if tools %} {{- '<|im_start|>system\n' }} {%- if messages[0]['role'] == 'system' %} {{- messages[0]['content'] }} {%- else %} {{- 'You are a helpful assistant.' }} {%- endif %} {{- "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }} {%- for tool in tools %} {{- "\n" }} {{- tool | tojson }} {%- endfor %} {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}{%- else %} {%- if messages[0]['role'] == 'system' %} {{- '<|im_start|>system\n' + messages[0]['content'] + '<|im_end|>\n' }} {%- else %} {{- '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n' }} {%- endif %}{%- endif %}{%- for message in messages %} {%- if (message.role == "user") or (message.role == "system" and not loop.first) or (message.role == "assistant" and not message.tool_calls) %} {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }} {%- elif message.role == "assistant" %} {{- '<|im_start|>' + message.role }} {%- if message.content %} {{- '\n' + message.content }} {%- endif %} {%- for tool_call in message.tool_calls %} {%- if tool_call.function is defined %} {%- set tool_call = tool_call.function %} {%- endif %} {{- '\n<tool_call>\n{"name": "' }} {{- tool_call.name }} {{- '", "arguments": ' }} {{- tool_call.arguments | tojson }} {{- '}\n</tool_call>' }} {%- endfor %} {{- '<|im_end|>\n' }} {%- elif message.role == "tool" %} {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") %} {{- '<|im_start|>user' }} {%- endif %} {{- '\n<tool_response>\n' }} {{- message.content }} {{- '\n</tool_response>' }} {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} {{- '<|im_end|>\n' }} {%- endif %} {%- endif %}{%- endfor %}{%- if add_generation_prompt %} {{- '<|im_start|>assistant\n' }}{%- endif %}12345678910111213141516171819202122232425262728293031323334{ "architectures": [ "MaincoderForCausalLM" ], "attention_dropout": 0.0, "auto_map": { "AutoConfig": "configuration_maincoder.MaincoderConfig", "AutoModel": "modelling_maincoder.MaincoderForCausalLM", "AutoModelForCausalLM": "modelling_maincoder.MaincoderForCausalLM" }, "bos_token_id": null, "eos_token_id": 151643, "head_dim": 96, "hidden_act": "silu", "hidden_size": 1536, "initializer_range": 0.02, "intermediate_size": 4096, "intermediate_size_mlp": 4096, "max_position_embeddings": 2048, "model_type": "maincoder", "num_attention_heads": 16, "num_hidden_layers": 32, "num_key_value_heads": 4, "pad_token_id": 151643, "rms_norm_eps": 1e-05, "rope_scaling": null, "rope_theta": 1000000.0, "tie_word_embeddings": true, "torch_dtype": "bfloat16", "transformers_version": "4.57.3", "use_cache": true, "use_qk_norm": true, "vocab_size": 151936}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141# coding=utf-8# Copyright 2025 Maincode. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Maincoder model configuration."""
from typing import Optional
from transformers.configuration_utils import PretrainedConfigfrom transformers.utils import logging
logger = logging.get_logger(__name__)
class MaincoderConfig(PretrainedConfig): r""" Configuration class for Maincoder model.
Args: vocab_size (`int`, *optional*, defaults to 151936): Vocabulary size of the Maincoder model. hidden_size (`int`, *optional*, defaults to 1536): Dimension of the hidden representations. intermediate_size (`int`, *optional*, defaults to 4096): Dimension of the MLP intermediate representations. intermediate_size_mlp (`int`, *optional*, defaults to 4096): Dimension of the MLP representations (same as intermediate_size for dense models). num_hidden_layers (`int`, *optional*, defaults to 32): Number of hidden layers in the Transformer decoder. num_attention_heads (`int`, *optional*, defaults to 16): Number of attention heads for each attention layer. num_key_value_heads (`int`, *optional*, defaults to 4): Number of key-value heads for Grouped Query Attention (GQA). head_dim (`int`, *optional*, defaults to 96): Dimension of each attention head. hidden_act (`str`, *optional*, defaults to `"silu"`): The activation function in the MLP. max_position_embeddings (`int`, *optional*, defaults to 2048): Maximum sequence length the model can handle. initializer_range (`float`, *optional*, defaults to 0.02): Standard deviation for weight initialization. rms_norm_eps (`float`, *optional*, defaults to 1e-05): Epsilon for RMS normalization layers. use_cache (`bool`, *optional*, defaults to `True`): Whether to use key-value cache for generation. pad_token_id (`int`, *optional*, defaults to 151643): Padding token id. bos_token_id (`int`, *optional*): Beginning of sequence token id. eos_token_id (`int`, *optional*, defaults to 151643): End of sequence token id. tie_word_embeddings (`bool`, *optional*, defaults to `True`): Whether to tie input and output embeddings. rope_theta (`float`, *optional*, defaults to 1000000.0): Base period for RoPE embeddings. rope_scaling (`Dict`, *optional*): RoPE scaling configuration for extended context. attention_dropout (`float`, *optional*, defaults to 0.0): Dropout probability for attention weights. use_qk_norm (`bool`, *optional*, defaults to `True`): Whether to apply RMS normalization to query and key.
Example: ```python >>> from configuration_maincoder import MaincoderConfig >>> from modelling_maincoder import MaincoderForCausalLM
>>> config = MaincoderConfig() >>> model = MaincoderForCausalLM(config) ``` """
model_type = "maincoder" keys_to_ignore_at_inference = ["past_key_values"]
def __init__( self, vocab_size: int = 151936, hidden_size: int = 1536, intermediate_size: int = 4096, intermediate_size_mlp: int = 4096, num_hidden_layers: int = 32, num_attention_heads: int = 16, num_key_value_heads: Optional[int] = 4, head_dim: Optional[int] = 96, hidden_act: str = "silu", max_position_embeddings: int = 2048, initializer_range: float = 0.02, rms_norm_eps: float = 1e-5, use_cache: bool = True, pad_token_id: Optional[int] = 151643, bos_token_id: Optional[int] = None, eos_token_id: int = 151643, tie_word_embeddings: bool = True, rope_theta: float = 1000000.0, rope_scaling: Optional[dict] = None, attention_dropout: float = 0.0, use_qk_norm: bool = True, **kwargs, ): self.vocab_size = vocab_size self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.intermediate_size_mlp = intermediate_size_mlp self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.max_position_embeddings = max_position_embeddings self.initializer_range = initializer_range self.rms_norm_eps = rms_norm_eps self.use_cache = use_cache self.rope_theta = rope_theta self.rope_scaling = rope_scaling self.attention_dropout = attention_dropout self.use_qk_norm = use_qk_norm self.hidden_act = hidden_act
# GQA configuration self.num_key_value_heads = num_key_value_heads if num_key_value_heads is not None else num_attention_heads self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
super().__init__( pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs, )
__all__ = ["MaincoderConfig"]1234567891011{ "_from_model_config": true, "eos_token_id": [ 151643, 128001, 128008, 128009 ], "pad_token_id": 151643, "transformers_version": "4.57.3"}123version https://git-lfs.github.com/spec/v1oid sha256:fde6820b5be360f5ebc2d3136b3ced4d0c11976c58a4770fe61b8f11912cfac9size 2052447608123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487# coding=utf-8# Copyright 2025 Maincode. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Maincoder model implementation."""
from typing import Callable, Optional, Union
import torchimport torch.nn as nn
from transformers.activations import ACT2FNfrom transformers.cache_utils import Cache, DynamicCachefrom transformers.generation import GenerationMixinfrom transformers.masking_utils import create_causal_maskfrom transformers.modeling_flash_attention_utils import FlashAttentionKwargsfrom transformers.modeling_layers import GradientCheckpointingLayerfrom transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPastfrom transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_updatefrom transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModelfrom transformers.processing_utils import Unpackfrom transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
from .configuration_maincoder import MaincoderConfig
logger = logging.get_logger(__name__)
class MaincoderRMSNorm(nn.Module): """RMSNorm implementation equivalent to T5LayerNorm."""
def __init__(self, hidden_size, eps=1e-5): """ MatildaPlusRMSNorm is equivalent to T5LayerNorm """ super().__init__() self.eps = eps self.weight = nn.Parameter(torch.ones(hidden_size))
def _norm(self, x): return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x): output = self._norm(x.float()).type_as(x) return output * self.weight
def extra_repr(self): return f"{tuple(self.weight.shape)}, eps={self.eps}"
class MaincoderMLP(nn.Module): """SwiGLU-style MLP."""
def __init__(self, config: MaincoderConfig): super().__init__() self.hidden_size = config.hidden_size self.intermediate_size = config.intermediate_size_mlp
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False) self.act_fn = ACT2FN[config.hidden_act]
def forward(self, x: torch.Tensor) -> torch.Tensor: return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
class MaincoderRotaryEmbedding(nn.Module): """Rotary Position Embedding."""
def __init__(self, config: MaincoderConfig, device=None): super().__init__() self.rope_type = "llama3" if config.rope_scaling is not None else "default" self.config = config self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device) self.register_buffer("inv_freq", inv_freq, persistent=False)
@torch.no_grad() @dynamic_rope_update def forward(self, x: torch.Tensor, position_ids: torch.Tensor) -> torch.Tensor: inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1) position_ids_expanded = position_ids[:, None, :].float()
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with torch.autocast(device_type=device_type, enabled=False): freqs = (inv_freq_expanded.to(x.device) @ position_ids_expanded).transpose(1, 2) freqs_cis = torch.polar(torch.ones_like(freqs), freqs) freqs_cis = freqs_cis * self.attention_scaling
return freqs_cis
def apply_rotary_emb( xq: torch.Tensor, xk: torch.Tensor, freqs_cis: torch.Tensor,) -> tuple[torch.Tensor, torch.Tensor]: """Apply rotary embeddings to query and key tensors.""" xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2)) xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
# Broadcast freqs_cis freqs_cis = freqs_cis[:, :, None, :]
xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3) xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
return xq_out.type_as(xq), xk_out.type_as(xk)
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """Repeat key/value heads to match query heads for GQA.""" if n_rep == 1: return hidden_states batch, num_kv_heads, slen, head_dim = hidden_states.shape hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_kv_heads, n_rep, slen, head_dim) return hidden_states.reshape(batch, num_kv_heads * n_rep, slen, head_dim)
def eager_attention_forward( module: nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: Optional[torch.Tensor], scaling: float, dropout: float = 0.0, **kwargs,) -> tuple[torch.Tensor, torch.Tensor]: """Eager attention implementation.""" key_states = repeat_kv(key, module.num_key_value_groups) value_states = repeat_kv(value, module.num_key_value_groups)
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
if attention_mask is not None: attn_weights = attn_weights + attention_mask[:, :, :, : key_states.shape[-2]]
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()
return attn_output, attn_weights
class MaincoderAttention(nn.Module): """Multi-headed attention with Grouped Query Attention (GQA) and RoPE."""
def __init__(self, config: MaincoderConfig, layer_idx: int): super().__init__() self.config = config self.layer_idx = layer_idx self.head_dim = config.head_dim self.num_attention_heads = config.num_attention_heads self.num_key_value_heads = config.num_key_value_heads self.num_key_value_groups = self.num_attention_heads // self.num_key_value_heads self.scaling = self.head_dim**-0.5 self.attention_dropout = config.attention_dropout
self.q_proj = nn.Linear(config.hidden_size, self.num_attention_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_attention_heads * self.head_dim, config.hidden_size, bias=False)
# QK normalization if config.use_qk_norm: self.q_norm = MaincoderRMSNorm(self.head_dim, eps=config.rms_norm_eps) self.k_norm = MaincoderRMSNorm(self.head_dim, eps=config.rms_norm_eps)
def forward( self, hidden_states: torch.Tensor, position_embeddings: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, past_key_values: Optional[Cache] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[FlashAttentionKwargs], ) -> tuple[torch.Tensor, Optional[torch.Tensor]]: batch_size, seq_len, _ = hidden_states.shape
query_states = self.q_proj(hidden_states).view(batch_size, seq_len, self.num_attention_heads, self.head_dim) key_states = self.k_proj(hidden_states).view(batch_size, seq_len, self.num_key_value_heads, self.head_dim) value_states = self.v_proj(hidden_states).view(batch_size, seq_len, self.num_key_value_heads, self.head_dim)
# Apply RoPE query_states, key_states = apply_rotary_emb(query_states, key_states, position_embeddings)
# Apply QK normalization if hasattr(self, "q_norm"): query_states = self.q_norm(query_states) key_states = self.k_norm(key_states)
# Transpose for attention: (batch, heads, seq, head_dim) query_states = query_states.transpose(1, 2) key_states = key_states.transpose(1, 2) value_states = value_states.transpose(1, 2)
# Update KV cache if past_key_values is not None: cache_kwargs = {"cache_position": cache_position} key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
# Attention attention_fn: Callable = eager_attention_forward if self.config._attn_implementation != "eager": attention_fn = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
attn_output, attn_weights = attention_fn( self, query_states, key_states, value_states, attention_mask, dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, **kwargs, )
attn_output = attn_output.reshape(batch_size, seq_len, -1) attn_output = self.o_proj(attn_output)
return attn_output, attn_weights
class MaincoderDecoderLayer(GradientCheckpointingLayer): """Transformer decoder layer with pre-norm architecture."""
def __init__(self, config: MaincoderConfig, layer_idx: int): super().__init__() self.self_attn = MaincoderAttention(config, layer_idx) self.feed_forward = MaincoderMLP(config) self.input_layernorm = MaincoderRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = MaincoderRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_embeddings: Optional[torch.Tensor] = None, past_key_values: Optional[Cache] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[FlashAttentionKwargs], ) -> torch.Tensor: # Self Attention residual = hidden_states hidden_states = self.input_layernorm(hidden_states) hidden_states, _ = self.self_attn( hidden_states=hidden_states, position_embeddings=position_embeddings, attention_mask=attention_mask, past_key_values=past_key_values, cache_position=cache_position, **kwargs, ) hidden_states = residual + hidden_states
# Feed Forward residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = self.feed_forward(hidden_states) hidden_states = residual + hidden_states
return hidden_states
@auto_docstringclass MaincoderPreTrainedModel(PreTrainedModel): """Base class for Maincoder models."""
config_class = MaincoderConfig base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["MaincoderDecoderLayer"] _skip_keys_device_placement = ["past_key_values"] _supports_sdpa = True _supports_flex_attn = True
def _init_weights(self, module: nn.Module): std = self.config.initializer_range if isinstance(module, nn.Linear): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() elif isinstance(module, MaincoderRMSNorm): module.weight.data.fill_(1.0)
@auto_docstringclass MaincoderModel(MaincoderPreTrainedModel): """Maincoder transformer model outputting raw hidden states."""
def __init__(self, config: MaincoderConfig): super().__init__(config) 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.layers = nn.ModuleList( [MaincoderDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.norm = MaincoderRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.rotary_emb = MaincoderRotaryEmbedding(config)
self.post_init()
@can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple, BaseModelOutputWithPast]: if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids)
if use_cache and past_key_values is None: past_key_values = DynamicCache()
if cache_position is None: 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], device=inputs_embeds.device, )
if position_ids is None: position_ids = cache_position.unsqueeze(0)
# Create causal mask causal_mask = create_causal_mask( config=self.config, input_embeds=inputs_embeds, attention_mask=attention_mask, cache_position=cache_position, past_key_values=past_key_values, )
# Position embeddings position_embeddings = self.rotary_emb(inputs_embeds, position_ids)
hidden_states = inputs_embeds for layer in self.layers: hidden_states = layer( hidden_states, attention_mask=causal_mask, position_embeddings=position_embeddings, past_key_values=past_key_values, cache_position=cache_position, **kwargs, )
hidden_states = self.norm(hidden_states)
return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=past_key_values if use_cache else None, )
class MaincoderForCausalLM(MaincoderPreTrainedModel, GenerationMixin): """Maincoder model with a causal language modeling head."""
_tied_weights_keys = ["lm_head.weight"]
def __init__(self, config: MaincoderConfig): super().__init__(config) self.model = MaincoderModel(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
self.post_init()
def get_input_embeddings(self) -> nn.Embedding: return self.model.embed_tokens
def set_input_embeddings(self, value: nn.Embedding): self.model.embed_tokens = value
def get_output_embeddings(self) -> nn.Linear: return self.lm_head
def set_output_embeddings(self, new_embeddings: nn.Linear): self.lm_head = new_embeddings
@can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple, CausalLMOutputWithPast]: r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
Example:
```python >>> from transformers import AutoTokenizer >>> from modelling_maincoder import MaincoderForCausalLM
>>> model = MaincoderForCausalLM.from_pretrained("maincoder/maincoder") >>> tokenizer = AutoTokenizer.from_pretrained("maincoder/maincoder")
>>> prompt = "def hello_world():" >>> inputs = tokenizer(prompt, return_tensors="pt")
>>> generate_ids = model.generate(inputs.input_ids, max_length=50) >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True)[0] ```""" outputs = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, cache_position=cache_position, **kwargs, )
hidden_states = outputs.last_hidden_state
# Only compute logits for tokens we need if isinstance(logits_to_keep, int) and logits_to_keep > 0: hidden_states = hidden_states[:, -logits_to_keep:, :]
logits = self.lm_head(hidden_states)
loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
__all__ = [ "MaincoderConfig", "MaincoderPreTrainedModel", "MaincoderModel", "MaincoderForCausalLM",]12345678910111213141516171819202122232425262728293031{ "additional_special_tokens": [ "<|im_start|>", "<|im_end|>", "<|object_ref_start|>", "<|object_ref_end|>", "<|box_start|>", "<|box_end|>", "<|quad_start|>", "<|quad_end|>", "<|vision_start|>", "<|vision_end|>", "<|vision_pad|>", "<|image_pad|>", "<|video_pad|>" ], "eos_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "pad_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }}123version https://git-lfs.github.com/spec/v1oid sha256:9c5ae00e602b8860cbd784ba82a8aa14e8feecec692e7076590d014d7b7fdafasize 11421896123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207{ "add_bos_token": false, "add_prefix_space": false, "added_tokens_decoder": { "151643": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151644": { "content": "<|im_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151645": { "content": "<|im_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151646": { "content": "<|object_ref_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151647": { "content": "<|object_ref_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151648": { "content": "<|box_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151649": { "content": "<|box_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151650": { "content": "<|quad_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151651": { "content": "<|quad_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151652": { "content": "<|vision_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151653": { "content": "<|vision_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151654": { "content": "<|vision_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151655": { "content": "<|image_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151656": { "content": "<|video_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151657": { "content": "<tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151658": { "content": "</tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151659": { "content": "<|fim_prefix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151660": { "content": "<|fim_middle|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151661": { "content": "<|fim_suffix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151662": { "content": "<|fim_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151663": { "content": "<|repo_name|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151664": { "content": "<|file_sep|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false } }, "additional_special_tokens": [ "<|im_start|>", "<|im_end|>", "<|object_ref_start|>", "<|object_ref_end|>", "<|box_start|>", "<|box_end|>", "<|quad_start|>", "<|quad_end|>", "<|vision_start|>", "<|vision_end|>", "<|vision_pad|>", "<|image_pad|>", "<|video_pad|>" ], "bos_token": null, "clean_up_tokenization_spaces": false, "eos_token": "<|endoftext|>", "errors": "replace", "extra_special_tokens": {}, "model_max_length": 32768, "pad_token": "<|endoftext|>", "split_special_tokens": false, "tokenizer_class": "Qwen2Tokenizer", "unk_token": null}.gitattributes+1
README.mdAdded+189
__init__.pyAdded+30
added_tokens.jsonAdded+24
chat_template.jinjaAdded+54
config.jsonAdded+34
configuration_maincoder.pyAdded+141
generation_config.jsonAdded+11
merges.txtAdded
model.safetensorsAdded+3
modelling_maincoder.pyAdded+487
special_tokens_map.jsonAdded+31
tokenizer.jsonAdded+3
tokenizer_config.jsonAdded+207
vocab.jsonAdded