Instructions to use IQuestLab/IQuest-Coder-V1-7B-Base with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use IQuestLab/IQuest-Coder-V1-7B-Base with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="IQuestLab/IQuest-Coder-V1-7B-Base", 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("IQuestLab/IQuest-Coder-V1-7B-Base", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use IQuestLab/IQuest-Coder-V1-7B-Base with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "IQuestLab/IQuest-Coder-V1-7B-Base" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "IQuestLab/IQuest-Coder-V1-7B-Base", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/IQuestLab/IQuest-Coder-V1-7B-Base
- SGLang
How to use IQuestLab/IQuest-Coder-V1-7B-Base 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 "IQuestLab/IQuest-Coder-V1-7B-Base" \ --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": "IQuestLab/IQuest-Coder-V1-7B-Base", "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 "IQuestLab/IQuest-Coder-V1-7B-Base" \ --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": "IQuestLab/IQuest-Coder-V1-7B-Base", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use IQuestLab/IQuest-Coder-V1-7B-Base with Docker Model Runner:
docker model run hf.co/IQuestLab/IQuest-Coder-V1-7B-Base
Upload folder using huggingface_hub
Browse filesFiles changed (17)
- .gitattributes+2
- LICENSE+26
- README.md+260-5
- config.jsonAdded+41
- configuration_iquestcoder.pyAdded+182
- generation_config.jsonAdded+6
- model-00001-of-00003.safetensorsAdded+3
- model-00002-of-00003.safetensorsAdded+3
- model-00003-of-00003.safetensorsAdded+3
- model.safetensors.index.jsonAdded+136
- modeling_iquestcoder.pyAdded+1068
- papers/iquest-coder-v1-logo.pngAdded
- papers/results.pngAdded
- tokenization_iquestcoder.pyAdded+552
- tokenizer.jsonAdded
- tokenizer.modelAdded+3
- tokenizer_config.jsonAdded+241
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 lines333435363732 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 -textpapers/iquest-coder-v1-logo.png filter=lfs diff=lfs merge=lfs -textpapers/results.png filter=lfs diff=lfs merge=lfs -text
1234567891011121314151617181920212223242526Modified MIT LicenseSoftware Copyright© 2025 IQuest ResearchOur only modification is that, if the Software (or any derivative worksthereof) is used for any of your commercial products or services, you shallprominently display "IQuest Coder" on the user interface of such product orservice.Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12345---license: otherlicense_name: modified-mitlicense_link: LICENSE---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260<p align="center">📘 <a href="https://iquestlab.github.io">Blog</a > • 📄 <a href="https://github.com/IQuestLab/IQuest-Coder-V1/blob/main/papers/IQuest_Coder_Technical_Report.pdf">Technical Report</a ></p ># IQuest-Coder-V1 Model Family## 7B Models| Model | Link ||-------|------|| IQuest-Coder-V1-7B-Base-Stage1 | [🤗 Hugging Face](https://huggingface.co/IQuestLab/IQuest-Coder-V1-7B-Base-Stage1) || IQuest-Coder-V1-7B-Base | [🤗 Hugging Face](https://huggingface.co/IQuestLab/IQuest-Coder-V1-7B-Base) || IQuest-Coder-V1-7B-Instruct | [🤗 Hugging Face](https://huggingface.co/IQuestLab/IQuest-Coder-V1-7B-Instruct) || IQuest-Coder-V1-7B-Thinking | [🤗 Hugging Face](https://huggingface.co/IQuestLab/IQuest-Coder-V1-7B-Thinking) |## 14B Models| Model | Link ||-------|------|| IQuest-Coder-V1-14B-Base-Stage1 | [🤗 Hugging Face](https://huggingface.co/IQuestLab/IQuest-Coder-V1-14B-Base-Stage1) || IQuest-Coder-V1-14B-Base | [🤗 Hugging Face](https://huggingface.co/IQuestLab/IQuest-Coder-V1-14B-Base) || IQuest-Coder-V1-14B-Instruct | [🤗 Hugging Face](https://huggingface.co/IQuestLab/IQuest-Coder-V1-14B-Instruct) || IQuest-Coder-V1-14B-Thinking | [🤗 Hugging Face](https://huggingface.co/IQuestLab/IQuest-Coder-V1-14B-Thinking) |## 40B Models| Model | Link ||-------|------|| IQuest-Coder-V1-40B-Base-Stage1 | [🤗 Hugging Face](https://huggingface.co/IQuestLab/IQuest-Coder-V1-40B-Base-Stage1) || IQuest-Coder-V1-40B-Base | [🤗 Hugging Face](https://huggingface.co/IQuestLab/IQuest-Coder-V1-40B-Base) || IQuest-Coder-V1-40B-Instruct | [🤗 Hugging Face](https://huggingface.co/IQuestLab/IQuest-Coder-V1-40B-Instruct) || IQuest-Coder-V1-40B-Loop-Instruct | [🤗 Hugging Face](https://huggingface.co/IQuestLab/IQuest-Coder-V1-40B-Loop-Instruct) || IQuest-Coder-V1-40B-Thinking | [🤗 Hugging Face](https://huggingface.co/IQuestLab/IQuest-Coder-V1-40B-Thinking) |## Sampling Parameters:For the IQuest-Coder-V1-Instruct: We suggest using Temperature=0.6, TopP=0.85, TopK=20.## IQuest-Coder-V1 HighlightsIQuest-Coder-V1 is a new family of code large language models (LLMs) designed to advance autonomous software engineering and code intelligence. Built on the innovative code-flow multi-stage training paradigm, IQuest-Coder-V1 captures the dynamic evolution of software logic, delivering state-of-the-art performance across critical dimensions:- **State-of-the-Art Performance**: Achieves leading results on SWE-Bench Verified, BigCodeBench, LiveCodeBench v6, and other major coding benchmarks, surpassing competitive models across agentic software engineering, competitive programming, and complex tool use.- **Code-Flow Training Paradigm**: Moving beyond static code representations, our models learn from repository evolution patterns, commit transitions, and dynamic code transformations to understand real-world software development processes.- **Dual Specialization Paths**: Bifurcated post-training delivers two specialized variants—Thinking models (utilizing reasoning-driven RL for complex problem-solving) and Instruct models (optimized for general coding assistance and instruction-following).- **Efficient Architecture**: The IQuest-Coder-V1-Loop variant introduces a recurrent mechanism that optimizes the trade-off between model capacity and deployment footprint. The 7B and 14B models adopt shallow architectures for faster inference speed.- **Native Long Context**: All models natively support up to 128K tokens without requiring additional scaling techniques.- **CLI Agent Integration**: Demonstrates initial deployment capabilities on ClaudeCode and OpenCode platforms, with the ability to integrate into CLI-based agent workflows.- **HTML and SVG Generation**: Features preliminary support for HTML and SVG code generation.## Model OverviewThe IQuest-Coder-V1 series includes models ranging from 7B to 40B parameters, with both standard and Loop variants:| Model | Parameters | Layers | Hidden Size | Attention Heads (Q/KV) | Context Length ||-------|------------|--------|-------------|------------------------|----------------|| IQuest-Coder-V1-7B-Instruct | 7B | 14 | 5120 | 40/8 | 128K || IQuest-Coder-V1-7B-Thinking | 7B | 14 | 5120 | 40/8 | 128K || IQuest-Coder-V1-14B-Instruct | 14B | 28 | 5120 | 40/8 | 128K || IQuest-Coder-V1-14B-Thinking | 14B | 28 | 5120 | 40/8 | 128K || IQuest-Coder-V1-40B-Instruct | 40B | 80 | 5120 | 40/8 | 128K || IQuest-Coder-V1-40B-Thinking | 40B | 80 | 5120 | 40/8 | 128K || IQuest-Coder-V1-40B-Loop-Instruct | 40B | 80 (2 iterations) | 5120 | 40/8 | 128K || IQuest-Coder-V1-40B-Loop-Thinking | 40B | 80 (2 iterations) | 5120 | 40/8 | 128K |**Architecture Features:**- Grouped Query Attention (GQA) for efficient inference- Native 128K context length support- Vocabulary size: 76,800 tokens- Loop variants use recurrent transformer design with shared parameters across two iterationsFor more details, please refer to our Technical Report, GitHub.## QuickstartIQuest-Coder-V1 uses custom modeling code via Hugging Face's auto_map feature. We recommend using transformers>=4.52.4.### Basic Usage with Transformers```pythonfrom transformers import AutoModelForCausalLM, AutoTokenizermodel_name = "IQuest/IQuest-Coder-V1-40B-Instruct"# Load the tokenizer and modeltokenizer = AutoTokenizer.from_pretrained(model_name)model = AutoModelForCausalLM.from_pretrained(model_name,torch_dtype="auto",device_map="auto")# Prepare the inputprompt = "Write a Python function to calculate the Fibonacci sequence using dynamic programming."messages = [{"role": "user", "content": prompt}]text = tokenizer.apply_chat_template(messages,tokenize=False,add_generation_prompt=True)model_inputs = tokenizer([text], return_tensors="pt").to(model.device)# Generate responsegenerated_ids = model.generate(**model_inputs,max_new_tokens=8192)generated_ids = generated_ids[0][len(model_inputs.input_ids[0]):]response = tokenizer.decode(generated_ids, skip_special_tokens=True)print(response)```### Using Thinking ModelsFor complex reasoning tasks, use the Thinking variant:```pythonmodel_name = "IQuestLab/IQuest-Coder-V1-40B-Thinking"# The Thinking model includes explicit reasoning traces# Use similar code as above, but expect longer, more detailed responses# with step-by-step problem decomposition```### Deployment with vLLMFor production deployment, you can use vLLM to create an OpenAI-compatible API endpoint. Please refer to the [vLLM PR](https://github.com/vllm-project/vllm/pull/31575/files) for implementation details.```bashvllm serve IQuestLab/IQuest-Coder-V1-40B-Instruct --tensor-parallel-size 8```For Thinking models with reasoning support:```bashvllm serve IQuestLab/IQuest-Coder-V1-40B-Thinking --reasoning-parser qwen3 --tensor-parallel-size 8```When using tool, `IQuest-Coder-V1-40B-Instruct` and `IQuest-Coder-V1-40B-Loop-Instruct` should use `--tool-parser qwen3`, while `IQuest-Coder-V1-7B-Instruct`, `IQuest-Coder-V1-7B-Thinking`, `IQuest-Coder-V1-14B-Instruct`, `IQuest-Coder-V1-14B-Thinking` and `IQuest-Coder-V1-40B-Thinking` should use `--tool-parser qwen3_coder`.### CLI-Like Agents and Tools UsageCLI-like agent capabilities are available for the following models: `IQuest-Coder-V1-7B-Instruct`, `IQuest-Coder-V1-7B-Thinking`, `IQuest-Coder-V1-14B-Instruct`, `IQuest-Coder-V1-14B-Thinking` and `IQuest-Coder-V1-40B-Thinking`.**Step 1:**: Deploy the model with vLLM and set tool parser (**Attention: Do not set reasoning parser for Instruct LLMs, otherwise it will cause unexpected errors**):```bashvllm serve IQuestLab/IQuest-Coder-V1-7B-Instruct --tool-parser qwen3_coder```or```bashvllm serve IQuestLab/IQuest-Coder-V1-7B-Thinking --tool-parser qwen3_coder --reasoning-parser qwen3```**Step 2:**: Use Claude Code to enjoy it:```bashexport ANTHROPIC_BASE_URL="http://iquestcoder.link"export ANTHROPIC_AUTH_TOKEN="sk-iquestcoder"claude --model IQuestCoder-V1-7B-Instruct```## Evaluation Results### Benchmark Parameters| Benchmark | Temperature | Top_p || :--- | :--- | :--- || **Evalplus-HumanEval** | 0.0 | - || **Evalplus-MBPP** | 0.0 | - || **BigCodeBench** | 0.0 | - || **FullStackBench** | 0.0 | - || **CruxEval** | 0.0 | - || **LiveCodeBench** | 0.6 | 0.95 || **Aider-Polyglot** | 0.95 | 0.85 || **Mercury** | 0.2 | 0.85 || **Bird** | 0.2 | 0.95 || **Spider** | 0.2 | 0.95 || **Terminal-Bench** | 0.0 | - || **Terminal-Bench (2.0)** | 0.7 | 1.0 || **SWE-Verified** | 0.0 | - || **BFCL V3** | 0.01 | 0.85 || **Mind2Web** | 0.0 | - |### SWE-Bench Verified EvaluationWe provide the evaluation framework and trajectory data for reproducing our SWE-Bench Verified results in `IQuest-Coder-Eval/SWE-Verified/`.The evaluation framework is based on [R2E-Gym](https://github.com/R2E-Gym/R2E-Gym). To reproduce the evaluation:```bashcd IQuest-Coder-Eval/SWE-Verified/R2E-Gym# Install dependenciespip install -e .# Run evaluationbash benchmark/bench/loopcoder/loopcoder.sh```The trajectory file `./IQuest-Coder-Eval/SWE-Verified/traj.zip` contains the complete agent trajectories for our SWE-Bench Verified evaluation.## Limitations- **Research Prototype**: The current models are designed for research purposes. Real-world user experience may differ from state-of-the-art commercial models, with weaker instruction-following capabilities in certain scenarios.- **Long-Context Management**: Due to parameter size constraints, performance on long-horizon tasks and multi-turn tool invocations is limited, particularly in scenarios requiring sustained context management and complex agentic workflows.- **Reasoning vs. Efficiency Trade-off**: Thinking models provide superior reasoning but generate longer responses; Instruct models are more efficient for straightforward tasks.- **Code Execution**: Models generate code but do not execute it; always validate outputs in sandboxed environments.- **Domain Specificity**: While trained on diverse codebases, performance may vary on highly specialized or proprietary frameworks.- **Factuality**: Models may generate plausible but incorrect code; verify critical implementations thoroughly.## CitationIf you find our work helpful, please cite:```bibtex@article{iquest-coder-v1-2025,title={IQuest-Coder-V1 Technical Report},author={IQuest Coder Team},url={https://github.com/IQuestLab/IQuest-Coder-V1/blob/main/papers/IQuest_Coder_Technical_Report.pdf}year={2025}}@article{codescaling,title={Scaling Laws for Code: Every Programming Language Matters},author={Yang, Jian and Guo, Shawn and Jing, Lin and Zhang, Wei and Liu, Aishan and Hao, Chuan and Li, Zhoujun and Zhao, Wayne Xin and Liu, Xianglong and Lv, Weifeng and others},journal={arXiv preprint arXiv:2512.13472},year={2025}}@article{close_the_loop,title={Close the Loop: Synthesizing Infinite Tool-Use Data via Multi-Agent Role-Playing},author={Yuwen Li, Wei Zhang, Zelong Huang, Mason Yang, Jiajun Wu, Shawn Guo, Huahao Hu, Lingyi Sun, Jian Yang, Mingjie Tang, Byran Dai},journal={arXiv preprint arXiv:2512.23611},year={2025}}@article{loopcoder,title={LoopCoder: Scaling Code Intelligence via Looped Language Models},author={Jian Yang, Wei Zhang, Shawn Guo, Yizhi Li, Lin Jing, Zhengmao Ye, Shark Liu, Yuyang Song, Jiajun Wu, Che Liu, T. Zheng, Siwei Wu, L. Liao, X. Ma, Chuan Hao, Ran Tao, Yan Xing, Jianzhou Wang, Mingjie Tang, Aishan Liu, Zhoujun Li, Xianglong Liu, Weifeng Lv1, Bryan Dai},year={2025}}@article{swe_compress,title={Context as a Tool: Context Management for Long-Horizon SWE-Agents},author={hukai Liu, Jian Yang, Bo Jiang, Yizhi Li, Jinyang Guo, Xianglong Liu, Bryan Dai},journal={arXiv preprint arXiv:2512.22087},year={2025}}```
1234567891011121314151617181920212223242526272829303132333435363738394041{ "architectures": [ "IQuestCoderForCausalLM" ], "attention_bias": false, "attention_dropout": 0.0, "bos_token_id": 1, "eos_token_id": [2, 75864, 75869], "head_dim": 128, "hidden_act": "silu", "hidden_size": 5120, "initializer_range": 0.02, "intermediate_size": 27648, "max_position_embeddings": 131072, "mlp_bias": false, "model_type": "iquestcoder", "num_attention_heads": 40, "num_hidden_layers": 14, "num_key_value_heads": 8, "pretraining_tp": 1, "rms_norm_eps": 1e-05, "rope_scaling": null, "rope_theta": 500000.0, "tie_word_embeddings": false, "torch_dtype": "bfloat16", "transformers_version": "4.55.4", "use_cache": true, "vocab_size": 76800, "clip_qkv": null, "use_sliding_window": false, "sliding_window": null, "max_window_layers": 0, "auto_map": { "AutoConfig": "configuration_iquestcoder.IQuestCoderConfig", "AutoModel": "modeling_iquestcoder.IQuestCoderModel", "AutoModelForCausalLM": "modeling_iquestcoder.IQuestCoderForCausalLM", "AutoModelForSequenceClassification": "modeling_iquestcoder.IQuestCoderForSequenceClassification", "AutoModelForTokenClassification": "modeling_iquestcoder.IQuestCoderForTokenClassification", "AutoModelForQuestionAnswering": "modeling_iquestcoder.IQuestCoderForQuestionAnswering" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182"""IQuestCoder model configuration."""
from transformers.configuration_utils import PretrainedConfigfrom transformers.utils import logging
logger = logging.get_logger(__name__)
class IQuestCoderConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`IQuestCoderModel`]. It is used to instantiate an IQuestCoder model according to the specified arguments, defining the model architecture.
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.
Args: vocab_size (`int`, *optional*, defaults to 76800): Vocabulary size of the IQuestCoder model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`IQuestCoderModel`]. hidden_size (`int`, *optional*, defaults to 5120): Dimension of the hidden representations. intermediate_size (`int`, *optional*, defaults to 27648): Dimension of the MLP representations. num_hidden_layers (`int`, *optional*, defaults to 80): Number of hidden layers in the Transformer decoder. num_attention_heads (`int`, *optional*, defaults to 40): Number of attention heads for each attention layer in the Transformer decoder. num_key_value_heads (`int`, *optional*, defaults to 8): This is the number of key_value heads that should be used to implement Grouped Query Attention (GQA). If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA). If `num_key_value_heads=1`, the model will use Multi Query Attention (MQA). head_dim (`int`, *optional*, defaults to 128): The dimension of each attention head. If not specified, defaults to `hidden_size // num_attention_heads`. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`): The non-linear activation function (function or string) in the decoder. max_position_embeddings (`int`, *optional*, defaults to 16384): The maximum sequence length that this model might ever be used with. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. rms_norm_eps (`float`, *optional*, defaults to 1e-05): The epsilon used by the rms normalization layers. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). pad_token_id (`int`, *optional*): Padding token id. bos_token_id (`int`, *optional*, defaults to 1): Beginning of stream token id. eos_token_id (`int`, *optional*, defaults to 2): End of stream token id. tie_word_embeddings (`bool`, *optional*, defaults to `False`): Whether to tie weight embeddings. rope_theta (`float`, *optional*, defaults to 500000.0): The base period of the RoPE embeddings. rope_scaling (`Dict`, *optional*): Dictionary containing the scaling configuration for the RoPE embeddings. Supports various RoPE scaling types including "linear", "dynamic", "yarn", "longrope", etc. attention_bias (`bool`, *optional*, defaults to `False`): Whether to use a bias in the query, key, value and output projection layers during self-attention. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities. mlp_bias (`bool`, *optional*, defaults to `False`): Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers. clip_qkv (`float`, *optional*): If set, clip the query, key, and value tensors to this value. Borrowed from OLMo for training stability. use_sliding_window (`bool`, *optional*, defaults to `False`): Whether to use sliding window attention. Borrowed from Qwen2. sliding_window (`int`, *optional*): The sliding window size. Only effective when `use_sliding_window=True`. max_window_layers (`int`, *optional*, defaults to 0): The number of layers that don't use sliding window attention. Borrowed from Qwen2.
Example: ```python >>> from configuration_iquestcoder import IQuestCoderConfig >>> from modeling_iquestcoder import IQuestCoderModel
>>> # Initializing a IQuestCoder configuration >>> configuration = IQuestCoderConfig()
>>> # Initializing a model from the configuration >>> model = IQuestCoderModel(configuration)
>>> # Accessing the model configuration >>> configuration = model.config ``` """
model_type = "iquestcoder" keys_to_ignore_at_inference = ["past_key_values"]
def __init__( self, vocab_size=76800, hidden_size=5120, intermediate_size=27648, num_hidden_layers=80, num_attention_heads=40, num_key_value_heads=8, head_dim=128, hidden_act="silu", max_position_embeddings=16384, initializer_range=0.02, rms_norm_eps=1e-5, use_cache=True, pad_token_id=None, bos_token_id=1, eos_token_id=2, tie_word_embeddings=False, rope_theta=500000.0, rope_scaling=None, attention_bias=False, attention_dropout=0.0, mlp_bias=False, # IQuestCoder specific (borrowed from OLMo) clip_qkv=None, # IQuestCoder specific (borrowed from Qwen2) use_sliding_window=False, sliding_window=None, max_window_layers=0, **kwargs, ): self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.head_dim = head_dim self.hidden_act = hidden_act 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_bias = attention_bias self.attention_dropout = attention_dropout self.mlp_bias = mlp_bias # IQuestCoder specific self.clip_qkv = clip_qkv self.use_sliding_window = use_sliding_window self.sliding_window = sliding_window self.max_window_layers = max_window_layers
# Validate rope_scaling configuration self._rope_scaling_validation()
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, )
def _rope_scaling_validation(self): """Validate the `rope_scaling` configuration.""" if self.rope_scaling is None: return
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) < 1: raise ValueError( "`rope_scaling` must be a dictionary with a minimum of one field, `type` or `rope_type`." ) rope_scaling_type = self.rope_scaling.get("type", None) or self.rope_scaling.get("rope_type", None) if rope_scaling_type is None: raise ValueError( "`rope_scaling` must have a `type` or `rope_type` field." ) valid_rope_types = ["linear", "dynamic", "yarn", "longrope", "llama3"] if rope_scaling_type not in valid_rope_types: raise ValueError( f"`rope_scaling`'s type field must be one of {valid_rope_types}, got {rope_scaling_type}" )
__all__ = ["IQuestCoderConfig"]
123456{ "_from_model_config": true, "bos_token_id": 1, "eos_token_id": [2, 75864, 75869], "transformers_version": "4.55.4"}123version https://git-lfs.github.com/spec/v1oid sha256:ed39a1ab76b49349a103b023658edd9a344f0e854c3386613009c889eeeebc8csize 5358309312123version https://git-lfs.github.com/spec/v1oid sha256:2ebe5b4c7c0e9c474ffe5a039a398b69b8af6a0bdcac50e535b2dfdc2a8608fasize 5274455712123version https://git-lfs.github.com/spec/v1oid sha256:e37f90292da43fea08469b07b155d639f3c319508a1f7dae57c6a2b4cfc9d665size 4592870344123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136{ "metadata": { "total_size": 15225620480 }, "weight_map": { "lm_head.weight": "model-00001-of-00003.safetensors", "model.embed_tokens.weight": "model-00001-of-00003.safetensors", "model.layers.0.input_layernorm.weight": "model-00001-of-00003.safetensors", "model.layers.0.mlp.down_proj.weight": "model-00001-of-00003.safetensors", "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00003.safetensors", "model.layers.0.mlp.up_proj.weight": "model-00001-of-00003.safetensors", "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00003.safetensors", "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00003.safetensors", "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00003.safetensors", "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00003.safetensors", "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00003.safetensors", "model.layers.1.input_layernorm.weight": "model-00001-of-00003.safetensors", "model.layers.1.mlp.down_proj.weight": "model-00001-of-00003.safetensors", "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00003.safetensors", "model.layers.1.mlp.up_proj.weight": "model-00001-of-00003.safetensors", "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00003.safetensors", "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00003.safetensors", "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00003.safetensors", "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00003.safetensors", "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00003.safetensors", "model.layers.10.input_layernorm.weight": "model-00001-of-00003.safetensors", "model.layers.10.mlp.down_proj.weight": "model-00001-of-00003.safetensors", "model.layers.10.mlp.gate_proj.weight": "model-00001-of-00003.safetensors", "model.layers.10.mlp.up_proj.weight": "model-00001-of-00003.safetensors", "model.layers.10.post_attention_layernorm.weight": "model-00001-of-00003.safetensors", "model.layers.10.self_attn.k_proj.weight": "model-00001-of-00003.safetensors", "model.layers.10.self_attn.o_proj.weight": "model-00001-of-00003.safetensors", "model.layers.10.self_attn.q_proj.weight": "model-00001-of-00003.safetensors", "model.layers.10.self_attn.v_proj.weight": "model-00001-of-00003.safetensors", "model.layers.11.input_layernorm.weight": "model-00001-of-00003.safetensors", "model.layers.11.mlp.down_proj.weight": "model-00001-of-00003.safetensors", "model.layers.11.mlp.gate_proj.weight": "model-00001-of-00003.safetensors", "model.layers.11.mlp.up_proj.weight": "model-00001-of-00003.safetensors", "model.layers.11.post_attention_layernorm.weight": "model-00001-of-00003.safetensors", "model.layers.11.self_attn.k_proj.weight": "model-00001-of-00003.safetensors", "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00003.safetensors", "model.layers.11.self_attn.q_proj.weight": "model-00002-of-00003.safetensors", "model.layers.11.self_attn.v_proj.weight": "model-00002-of-00003.safetensors", "model.layers.12.input_layernorm.weight": "model-00002-of-00003.safetensors", "model.layers.12.mlp.down_proj.weight": "model-00002-of-00003.safetensors", "model.layers.12.mlp.gate_proj.weight": "model-00002-of-00003.safetensors", "model.layers.12.mlp.up_proj.weight": "model-00002-of-00003.safetensors", "model.layers.12.post_attention_layernorm.weight": "model-00002-of-00003.safetensors", "model.layers.12.self_attn.k_proj.weight": "model-00002-of-00003.safetensors", "model.layers.12.self_attn.o_proj.weight": "model-00002-of-00003.safetensors", "model.layers.12.self_attn.q_proj.weight": "model-00002-of-00003.safetensors", "model.layers.12.self_attn.v_proj.weight": "model-00002-of-00003.safetensors", "model.layers.13.input_layernorm.weight": "model-00002-of-00003.safetensors", "model.layers.13.mlp.down_proj.weight": "model-00002-of-00003.safetensors", "model.layers.13.mlp.gate_proj.weight": "model-00002-of-00003.safetensors", "model.layers.13.mlp.up_proj.weight": "model-00002-of-00003.safetensors", "model.layers.13.post_attention_layernorm.weight": "model-00002-of-00003.safetensors", "model.layers.13.self_attn.k_proj.weight": "model-00002-of-00003.safetensors", "model.layers.13.self_attn.o_proj.weight": "model-00002-of-00003.safetensors", "model.layers.13.self_attn.q_proj.weight": "model-00002-of-00003.safetensors", "model.layers.13.self_attn.v_proj.weight": "model-00002-of-00003.safetensors", "model.layers.2.input_layernorm.weight": "model-00002-of-00003.safetensors", "model.layers.2.mlp.down_proj.weight": "model-00002-of-00003.safetensors", "model.layers.2.mlp.gate_proj.weight": "model-00002-of-00003.safetensors", "model.layers.2.mlp.up_proj.weight": "model-00002-of-00003.safetensors", "model.layers.2.post_attention_layernorm.weight": "model-00002-of-00003.safetensors", "model.layers.2.self_attn.k_proj.weight": "model-00002-of-00003.safetensors", "model.layers.2.self_attn.o_proj.weight": "model-00002-of-00003.safetensors", "model.layers.2.self_attn.q_proj.weight": "model-00002-of-00003.safetensors", "model.layers.2.self_attn.v_proj.weight": "model-00002-of-00003.safetensors", "model.layers.3.input_layernorm.weight": "model-00002-of-00003.safetensors", "model.layers.3.mlp.down_proj.weight": "model-00002-of-00003.safetensors", "model.layers.3.mlp.gate_proj.weight": "model-00002-of-00003.safetensors", "model.layers.3.mlp.up_proj.weight": "model-00002-of-00003.safetensors", "model.layers.3.post_attention_layernorm.weight": "model-00002-of-00003.safetensors", "model.layers.3.self_attn.k_proj.weight": "model-00002-of-00003.safetensors", "model.layers.3.self_attn.o_proj.weight": "model-00002-of-00003.safetensors", "model.layers.3.self_attn.q_proj.weight": "model-00002-of-00003.safetensors", "model.layers.3.self_attn.v_proj.weight": "model-00002-of-00003.safetensors", "model.layers.4.input_layernorm.weight": "model-00002-of-00003.safetensors", "model.layers.4.mlp.down_proj.weight": "model-00002-of-00003.safetensors", "model.layers.4.mlp.gate_proj.weight": "model-00002-of-00003.safetensors", "model.layers.4.mlp.up_proj.weight": "model-00002-of-00003.safetensors", "model.layers.4.post_attention_layernorm.weight": "model-00002-of-00003.safetensors", "model.layers.4.self_attn.k_proj.weight": "model-00002-of-00003.safetensors", "model.layers.4.self_attn.o_proj.weight": "model-00002-of-00003.safetensors", "model.layers.4.self_attn.q_proj.weight": "model-00002-of-00003.safetensors", "model.layers.4.self_attn.v_proj.weight": "model-00002-of-00003.safetensors", "model.layers.5.input_layernorm.weight": "model-00002-of-00003.safetensors", "model.layers.5.mlp.down_proj.weight": "model-00002-of-00003.safetensors", "model.layers.5.mlp.gate_proj.weight": "model-00003-of-00003.safetensors", "model.layers.5.mlp.up_proj.weight": "model-00003-of-00003.safetensors", "model.layers.5.post_attention_layernorm.weight": "model-00003-of-00003.safetensors", "model.layers.5.self_attn.k_proj.weight": "model-00003-of-00003.safetensors", "model.layers.5.self_attn.o_proj.weight": "model-00003-of-00003.safetensors", "model.layers.5.self_attn.q_proj.weight": "model-00003-of-00003.safetensors", "model.layers.5.self_attn.v_proj.weight": "model-00003-of-00003.safetensors", "model.layers.6.input_layernorm.weight": "model-00003-of-00003.safetensors", "model.layers.6.mlp.down_proj.weight": "model-00003-of-00003.safetensors", "model.layers.6.mlp.gate_proj.weight": "model-00003-of-00003.safetensors", "model.layers.6.mlp.up_proj.weight": "model-00003-of-00003.safetensors", "model.layers.6.post_attention_layernorm.weight": "model-00003-of-00003.safetensors", "model.layers.6.self_attn.k_proj.weight": "model-00003-of-00003.safetensors", "model.layers.6.self_attn.o_proj.weight": "model-00003-of-00003.safetensors", "model.layers.6.self_attn.q_proj.weight": "model-00003-of-00003.safetensors", "model.layers.6.self_attn.v_proj.weight": "model-00003-of-00003.safetensors", "model.layers.7.input_layernorm.weight": "model-00003-of-00003.safetensors", "model.layers.7.mlp.down_proj.weight": "model-00003-of-00003.safetensors", "model.layers.7.mlp.gate_proj.weight": "model-00003-of-00003.safetensors", "model.layers.7.mlp.up_proj.weight": "model-00003-of-00003.safetensors", "model.layers.7.post_attention_layernorm.weight": "model-00003-of-00003.safetensors", "model.layers.7.self_attn.k_proj.weight": "model-00003-of-00003.safetensors", "model.layers.7.self_attn.o_proj.weight": "model-00003-of-00003.safetensors", "model.layers.7.self_attn.q_proj.weight": "model-00003-of-00003.safetensors", "model.layers.7.self_attn.v_proj.weight": "model-00003-of-00003.safetensors", "model.layers.8.input_layernorm.weight": "model-00003-of-00003.safetensors", "model.layers.8.mlp.down_proj.weight": "model-00003-of-00003.safetensors", "model.layers.8.mlp.gate_proj.weight": "model-00003-of-00003.safetensors", "model.layers.8.mlp.up_proj.weight": "model-00003-of-00003.safetensors", "model.layers.8.post_attention_layernorm.weight": "model-00003-of-00003.safetensors", "model.layers.8.self_attn.k_proj.weight": "model-00003-of-00003.safetensors", "model.layers.8.self_attn.o_proj.weight": "model-00003-of-00003.safetensors", "model.layers.8.self_attn.q_proj.weight": "model-00003-of-00003.safetensors", "model.layers.8.self_attn.v_proj.weight": "model-00003-of-00003.safetensors", "model.layers.9.input_layernorm.weight": "model-00003-of-00003.safetensors", "model.layers.9.mlp.down_proj.weight": "model-00003-of-00003.safetensors", "model.layers.9.mlp.gate_proj.weight": "model-00003-of-00003.safetensors", "model.layers.9.mlp.up_proj.weight": "model-00003-of-00003.safetensors", "model.layers.9.post_attention_layernorm.weight": "model-00003-of-00003.safetensors", "model.layers.9.self_attn.k_proj.weight": "model-00003-of-00003.safetensors", "model.layers.9.self_attn.o_proj.weight": "model-00003-of-00003.safetensors", "model.layers.9.self_attn.q_proj.weight": "model-00003-of-00003.safetensors", "model.layers.9.self_attn.v_proj.weight": "model-00003-of-00003.safetensors", "model.norm.weight": "model-00003-of-00003.safetensors" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068"""Modified MIT License
Software Copyright© 2025 IQuest Research
Our only modification is that, if the Software (or any derivative worksthereof) is used for any of your commercial products or services, you shallprominently display "IQuest Coder" on the user interface of such product orservice.Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."""
from typing import Callable, List, Optional, Tuple, Union
import torchimport torch.nn as nnimport torch.nn.functional as F
from transformers.activations import ACT2FNfrom transformers.cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCachefrom transformers.generation import GenerationMixinfrom transformers.modeling_attn_mask_utils import AttentionMaskConverterfrom transformers.modeling_flash_attention_utils import FlashAttentionKwargsfrom transformers.modeling_layers import GradientCheckpointingLayerfrom transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast, QuestionAnsweringModelOutput, SequenceClassifierOutputWithPast, TokenClassifierOutput,)from 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 ( LossKwargs, auto_docstring, can_return_tuple, is_torch_flex_attn_available, logging,)
from .configuration_iquestcoder import IQuestCoderConfig
if is_torch_flex_attn_available(): from torch.nn.attention.flex_attention import BlockMask from transformers.integrations.flex_attention import make_flex_block_causal_mask
logger = logging.get_logger(__name__)
# =============================================================================# Helper Functions# =============================================================================
def rotate_half(x: torch.Tensor) -> torch.Tensor: """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1)
def apply_rotary_pos_emb( q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, position_ids: Optional[torch.Tensor] = None, unsqueeze_dim: int = 1,) -> Tuple[torch.Tensor, torch.Tensor]: """Applies Rotary Position Embedding to the query and key tensors.
Args: q: The query tensor. k: The key tensor. cos: The cosine part of the rotary embedding. sin: The sine part of the rotary embedding. position_ids: Deprecated and unused. unsqueeze_dim: The dimension along which to unsqueeze cos and sin.
Returns: Tuple of query and key tensors rotated using the Rotary Position Embedding. """ # Borrowed from OLMo: preserve original dtypes for numerical stability q_dtype, k_dtype = q.dtype, k.dtype cos = cos.unsqueeze(unsqueeze_dim) sin = sin.unsqueeze(unsqueeze_dim) q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed.to(q_dtype), k_embed.to(k_dtype)
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ Expands key/value heads for Grouped Query Attention. This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim). """ 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) return hidden_states.reshape(batch, num_key_value_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]: """Standard 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: causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] attn_weights = attn_weights + causal_mask
attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) attn_weights = F.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
# =============================================================================# Model Components# =============================================================================
class IQuestCoderRMSNorm(nn.Module): """Root Mean Square Layer Normalization. RMSNorm is computationally simpler than LayerNorm while achieving similar performance. It normalizes the input by its RMS value. """
def __init__(self, hidden_size: int, eps: float = 1e-6): super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) return self.weight * hidden_states.to(input_dtype)
def extra_repr(self) -> str: return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
class IQuestCoderRotaryEmbedding(nn.Module): """Rotary Position Embedding (RoPE). Implements rotary positional embeddings as described in the RoFormer paper. Supports various RoPE scaling methods for extended context lengths. """
def __init__(self, config: IQuestCoderConfig, device=None): super().__init__() # BC: "rope_type" was originally "type" if hasattr(config, "rope_scaling") and config.rope_scaling is not None: self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type")) else: self.rope_type = "default" self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings
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) self.original_inv_freq = self.inv_freq
@torch.no_grad() @dynamic_rope_update def forward(self, x: torch.Tensor, position_ids: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device) 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.float() @ position_ids_expanded.float()).transpose(1, 2) emb = torch.cat((freqs, freqs), dim=-1) cos = emb.cos() * self.attention_scaling sin = emb.sin() * self.attention_scaling
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
class IQuestCoderMLP(nn.Module): """Feed-forward network with SwiGLU activation. Uses the gated linear unit variant with SiLU activation for improved performance compared to standard FFN. """
def __init__(self, config: IQuestCoderConfig): super().__init__() self.config = config self.hidden_size = config.hidden_size self.intermediate_size = config.intermediate_size self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias) self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias) self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias) self.act_fn = ACT2FN[config.hidden_act]
def forward(self, x: torch.Tensor) -> torch.Tensor: # SwiGLU: down_proj(act_fn(gate_proj(x)) * up_proj(x)) return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
class IQuestCoderAttention(nn.Module): """Multi-headed attention with support for Grouped Query Attention (GQA). Features: - Grouped Query Attention for memory efficiency - Optional QKV clipping for training stability (from OLMo) - Optional sliding window attention (from Qwen2) - Rotary Position Embeddings """
def __init__(self, config: IQuestCoderConfig, layer_idx: int): super().__init__() self.config = config self.layer_idx = layer_idx self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads) self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads self.scaling = self.head_dim ** -0.5 self.attention_dropout = config.attention_dropout self.is_causal = True
# Projection layers self.q_proj = nn.Linear( config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias ) self.k_proj = nn.Linear( config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias ) self.v_proj = nn.Linear( config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias ) self.o_proj = nn.Linear( config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias )
def forward( self, hidden_states: torch.Tensor, position_embeddings: Tuple[torch.Tensor, torch.Tensor], attention_mask: Optional[torch.Tensor], past_key_value: Optional[Cache] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[FlashAttentionKwargs], ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: input_shape = hidden_states.shape[:-1] hidden_shape = (*input_shape, -1, self.head_dim)
# Compute Q, K, V projections query_states = self.q_proj(hidden_states) key_states = self.k_proj(hidden_states) value_states = self.v_proj(hidden_states)
# [OLMo Feature] Optional QKV clipping for training stability if self.config.clip_qkv is not None: query_states = query_states.clamp(min=-self.config.clip_qkv, max=self.config.clip_qkv) key_states = key_states.clamp(min=-self.config.clip_qkv, max=self.config.clip_qkv) value_states = value_states.clamp(min=-self.config.clip_qkv, max=self.config.clip_qkv)
# Reshape to (batch, heads, seq_len, head_dim) query_states = query_states.view(hidden_shape).transpose(1, 2) key_states = key_states.view(hidden_shape).transpose(1, 2) value_states = value_states.view(hidden_shape).transpose(1, 2)
# Apply rotary position embeddings cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
# Update KV cache if provided if past_key_value is not None: cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
# [Qwen2 Feature] Sliding window attention sliding_window = None if ( self.config.use_sliding_window and getattr(self.config, "sliding_window", None) is not None and self.layer_idx >= self.config.max_window_layers ): sliding_window = self.config.sliding_window
# Select attention implementation attention_interface: Callable = eager_attention_forward if self.config._attn_implementation != "eager": if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False): logger.warning_once( "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. " 'Falling back to eager attention. This warning can be removed using the argument ' '`attn_implementation="eager"` when loading the model.' ) else: attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
# Compute attention attn_output, attn_weights = attention_interface( self, query_states, key_states, value_states, attention_mask, dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, sliding_window=sliding_window, **kwargs, )
# Reshape and project output attn_output = attn_output.reshape(*input_shape, -1).contiguous() attn_output = self.o_proj(attn_output)
return attn_output, attn_weights
class IQuestCoderDecoderLayer(GradientCheckpointingLayer): """Transformer decoder layer with pre-normalization. Architecture: Pre-RMSNorm -> Attention -> Residual -> Pre-RMSNorm -> MLP -> Residual """
def __init__(self, config: IQuestCoderConfig, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.self_attn = IQuestCoderAttention(config=config, layer_idx=layer_idx) self.mlp = IQuestCoderMLP(config) self.input_layernorm = IQuestCoderRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = IQuestCoderRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
# Warn if sliding window is enabled but not properly supported if config.use_sliding_window and config._attn_implementation != "flash_attention_2": logger.warning_once( f"Sliding Window Attention is enabled but not implemented for `{config._attn_implementation}`; " "unexpected results may be encountered." )
def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Cache] = None, output_attentions: Optional[bool] = False, use_cache: Optional[bool] = False, cache_position: Optional[torch.LongTensor] = None, position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, **kwargs: Unpack[FlashAttentionKwargs], ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: # Pre-norm + Self Attention residual = hidden_states hidden_states = self.input_layernorm(hidden_states)
hidden_states, self_attn_weights = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_value, output_attentions=output_attentions, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, **kwargs, ) hidden_states = residual + hidden_states
# Pre-norm + MLP residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = residual + hidden_states
outputs = (hidden_states,) if output_attentions: outputs += (self_attn_weights,)
return outputs
# =============================================================================# Base Model# =============================================================================
@auto_docstringclass IQuestCoderPreTrainedModel(PreTrainedModel): """Base class for IQuestCoder models."""
config_class = IQuestCoderConfig base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["IQuestCoderDecoderLayer"] _skip_keys_device_placement = ["past_key_values"] _supports_flash_attn_2 = True _supports_sdpa = True _supports_flex_attn = True _supports_cache_class = True _supports_quantized_cache = True _supports_static_cache = True _supports_attention_backend = 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, IQuestCoderRMSNorm): module.weight.data.fill_(1.0)
@auto_docstringclass IQuestCoderModel(IQuestCoderPreTrainedModel): """ IQuestCoder Model outputting raw hidden-states without any specific head on top. This model is compatible with LLaMA weights while incorporating features from OLMo and Qwen2. """
def __init__(self, config: IQuestCoderConfig): 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( [IQuestCoderDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.norm = IQuestCoderRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.rotary_emb = IQuestCoderRotaryEmbedding(config=config) self.gradient_checkpointing = False
# Initialize weights and apply final processing self.post_init()
def get_input_embeddings(self) -> nn.Embedding: return self.embed_tokens
def set_input_embeddings(self, value: nn.Embedding): self.embed_tokens = value
@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, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, **flash_attn_kwargs: Unpack[FlashAttentionKwargs], ) -> BaseModelOutputWithPast: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache
if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if self.gradient_checkpointing and self.training and use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`." ) use_cache = False
if not isinstance(past_key_values, (type(None), Cache)): raise ValueError("The `past_key_values` should be either a `Cache` object or `None`.")
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)
causal_mask = self._update_causal_mask( attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions )
hidden_states = inputs_embeds
# Create position embeddings to be shared across the decoder layers position_embeddings = self.rotary_emb(hidden_states, position_ids)
# Decoder layers all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None
for decoder_layer in self.layers[: self.config.num_hidden_layers]: if output_hidden_states: all_hidden_states += (hidden_states,)
layer_outputs = decoder_layer( hidden_states, attention_mask=causal_mask, position_ids=position_ids, past_key_value=past_key_values, output_attentions=output_attentions, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, **flash_attn_kwargs, )
hidden_states = layer_outputs[0]
if output_attentions: all_self_attns += (layer_outputs[1],)
hidden_states = self.norm(hidden_states)
# Add hidden states from the last decoder layer if output_hidden_states: all_hidden_states += (hidden_states,)
return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=past_key_values if use_cache else None, hidden_states=all_hidden_states, attentions=all_self_attns, )
def _update_causal_mask( self, attention_mask: Union[torch.Tensor, "BlockMask"], input_tensor: torch.Tensor, cache_position: torch.Tensor, past_key_values: Cache, output_attentions: bool = False, ): if self.config._attn_implementation == "flash_attention_2": if attention_mask is not None and past_key_values is not None: is_padding_right = attention_mask[:, -1].sum().item() != input_tensor.size()[0] if is_padding_right: raise ValueError( "You are attempting to perform batched generation with padding_side='right'. " "This may lead to unexpected behaviour for Flash Attention version of IQuestCoder. " "Make sure to call `tokenizer.padding_side = 'left'` before tokenizing the input." ) if attention_mask is not None and 0.0 in attention_mask: return attention_mask return None
if self.config._attn_implementation == "flex_attention": if isinstance(attention_mask, torch.Tensor): attention_mask = make_flex_block_causal_mask(attention_mask) return attention_mask
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 using_static_cache = isinstance(past_key_values, StaticCache) using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)
if ( self.config._attn_implementation == "sdpa" and not (using_static_cache or using_sliding_window_cache) and not output_attentions ): if AttentionMaskConverter._ignore_causal_mask_sdpa( attention_mask, inputs_embeds=input_tensor, past_key_values_length=past_seen_tokens, sliding_window=self.config.sliding_window if self.config.use_sliding_window else None, is_training=self.training, ): return None
dtype = input_tensor.dtype min_dtype = torch.finfo(dtype).min sequence_length = input_tensor.shape[1]
if using_sliding_window_cache or using_static_cache: target_length = past_key_values.get_max_cache_shape() else: target_length = ( attention_mask.shape[-1] if isinstance(attention_mask, torch.Tensor) else past_seen_tokens + sequence_length + 1 )
causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position( attention_mask, sequence_length=sequence_length, target_length=target_length, dtype=dtype, cache_position=cache_position, batch_size=input_tensor.shape[0], config=self.config, past_key_values=past_key_values, )
if ( self.config._attn_implementation == "sdpa" and attention_mask is not None and attention_mask.device.type in ["cuda", "xpu", "npu"] and not output_attentions ): causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
return causal_mask
@staticmethod def _prepare_4d_causal_attention_mask_with_cache_position( attention_mask: torch.Tensor, sequence_length: int, target_length: int, dtype: torch.dtype, cache_position: torch.Tensor, batch_size: int, config: IQuestCoderConfig, past_key_values: Cache, ): """Creates a causal 4D mask from a 2D mask, or returns the 4D mask if already provided.""" if attention_mask is not None and attention_mask.dim() == 4: causal_mask = attention_mask else: min_dtype = torch.finfo(dtype).min causal_mask = torch.full( (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device ) diagonal_attend_mask = torch.arange(target_length, device=cache_position.device) > cache_position.reshape( -1, 1 ) # [Qwen2 Feature] Handle sliding window mask if getattr(config, "use_sliding_window", False) and config.sliding_window is not None: if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length: sliding_attend_mask = torch.arange(target_length, device=cache_position.device) <= ( cache_position.reshape(-1, 1) - config.sliding_window ) diagonal_attend_mask.bitwise_or_(sliding_attend_mask) causal_mask *= diagonal_attend_mask causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1) if attention_mask is not None: causal_mask = causal_mask.clone() if attention_mask.shape[-1] > target_length: attention_mask = attention_mask[:, :target_length] mask_length = attention_mask.shape[-1] padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to( causal_mask.device ) padding_mask = padding_mask == 0 causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill( padding_mask, min_dtype )
return causal_mask
# =============================================================================# Model Heads# =============================================================================
class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
@auto_docstringclass IQuestCoderForCausalLM(IQuestCoderPreTrainedModel, GenerationMixin): """IQuestCoder Model with a language modeling head on top for causal LM."""
_tied_weights_keys = ["lm_head.weight"] _tp_plan = {"lm_head": "colwise_rep"} _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config: IQuestCoderConfig): super().__init__(config) self.model = IQuestCoderModel(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# Initialize weights and apply final processing 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
def set_decoder(self, decoder: IQuestCoderModel): self.model = decoder
def get_decoder(self) -> IQuestCoderModel: return self.model
@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, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs: Unpack[KwargsForCausalLM], ) -> CausalLMOutputWithPast: r""" Args: 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 modeling_iquestcoder import IQuestCoderForCausalLM
>>> model = IQuestCoderForCausalLM.from_pretrained("path/to/IQuestCoder") >>> tokenizer = AutoTokenizer.from_pretrained("path/to/IQuestCoder")
>>> prompt = "Hey, are you conscious? Can you talk to me?" >>> inputs = tokenizer(prompt, return_tensors="pt")
>>> # Generate >>> generate_ids = model.generate(inputs.input_ids, max_length=30) >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] "Hey, are you conscious? Can you talk to me?\\nI'm not conscious, but I can talk to you." ``` """ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states )
# Decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) outputs: BaseModelOutputWithPast = 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, output_attentions=output_attentions, output_hidden_states=output_hidden_states, cache_position=cache_position, **kwargs, )
hidden_states = outputs.last_hidden_state # Only compute necessary logits, and do not upcast them to float if we are not computing the loss 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=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, )
@auto_docstring( custom_intro=""" The IQuestCoder Model transformer with a sequence classification head on top (linear layer).
[`IQuestCoderForSequenceClassification`] uses the last token in order to do the classification, as other causal models (e.g. GPT-2) do.
Since it does classification on the last token, it requires to know the position of the last token. If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If no `pad_token_id` is defined, it simply takes the last value in each row of the batch. """)class IQuestCoderForSequenceClassification(IQuestCoderPreTrainedModel): """IQuestCoder Model with a sequence classification head."""
def __init__(self, config: IQuestCoderConfig): super().__init__(config) self.num_labels = config.num_labels self.model = IQuestCoderModel(config) self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
# Initialize weights and apply final processing 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
@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, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, ) -> SequenceClassifierOutputWithPast: r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ transformer_outputs: BaseModelOutputWithPast = self.model( input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, ) hidden_states = transformer_outputs.last_hidden_state logits = self.score(hidden_states)
if input_ids is not None: batch_size = input_ids.shape[0] else: batch_size = inputs_embeds.shape[0]
if self.config.pad_token_id is None and batch_size != 1: raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.") if self.config.pad_token_id is None: last_non_pad_token = -1 elif input_ids is not None: non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32) token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32) last_non_pad_token = (token_indices * non_pad_mask).argmax(-1) else: last_non_pad_token = -1 logger.warning_once( f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be " "unexpected if using padding tokens in conjunction with `inputs_embeds.`" )
pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
return SequenceClassifierOutputWithPast( loss=loss, logits=pooled_logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, )
@auto_docstringclass IQuestCoderForTokenClassification(IQuestCoderPreTrainedModel): """IQuestCoder Model with a token classification head."""
def __init__(self, config: IQuestCoderConfig): super().__init__(config) self.num_labels = config.num_labels self.model = IQuestCoderModel(config) if getattr(config, "classifier_dropout", None) is not None: classifier_dropout = config.classifier_dropout elif getattr(config, "hidden_dropout", None) is not None: classifier_dropout = config.hidden_dropout else: classifier_dropout = 0.1 self.dropout = nn.Dropout(classifier_dropout) self.score = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing 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
@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, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, ) -> TokenClassifierOutput: r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ outputs: BaseModelOutputWithPast = self.model( input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, ) sequence_output = outputs.last_hidden_state sequence_output = self.dropout(sequence_output) logits = self.score(sequence_output)
loss = None if labels is not None: loss = self.loss_function(logits, labels, self.config)
return TokenClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
@auto_docstringclass IQuestCoderForQuestionAnswering(IQuestCoderPreTrainedModel): """IQuestCoder Model with a span classification head for extractive question-answering."""
base_model_prefix = "transformer"
def __init__(self, config: IQuestCoderConfig): super().__init__(config) self.transformer = IQuestCoderModel(config) self.qa_outputs = nn.Linear(config.hidden_size, 2)
# Initialize weights and apply final processing self.post_init()
def get_input_embeddings(self) -> nn.Embedding: return self.transformer.embed_tokens
def set_input_embeddings(self, value: nn.Embedding): self.transformer.embed_tokens = value
@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, start_positions: Optional[torch.LongTensor] = None, end_positions: Optional[torch.LongTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, **kwargs, ) -> QuestionAnsweringModelOutput: outputs: BaseModelOutputWithPast = self.transformer( input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, )
sequence_output = outputs.last_hidden_state
logits = self.qa_outputs(sequence_output) start_logits, end_logits = logits.split(1, dim=-1) start_logits = start_logits.squeeze(-1).contiguous() end_logits = end_logits.squeeze(-1).contiguous()
loss = None if start_positions is not None and end_positions is not None: loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
return QuestionAnsweringModelOutput( loss=loss, start_logits=start_logits, end_logits=end_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
__all__ = [ "IQuestCoderPreTrainedModel", "IQuestCoderModel", "IQuestCoderForCausalLM", "IQuestCoderForSequenceClassification", "IQuestCoderForTokenClassification", "IQuestCoderForQuestionAnswering",]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552"""Tokenization classes for IQuestCoder."""
import osfrom shutil import copyfilefrom typing import Any, Dict, List, Optional, Tuple, Union
import sentencepiece as spm
from transformers.tokenization_utils import AddedToken, PreTrainedTokenizerfrom transformers.utils import logging
logger = logging.get_logger(__name__)
VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
PRETRAINED_VOCAB_FILES_MAP = { "vocab_file": {}, "tokenizer_file": {},}PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {}
class IQuestCoderTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES model_input_names = ["input_ids", "attention_mask"]
def __init__( self, vocab_file, unk_token="<unk>", bos_token="<s>", eos_token="</s>", pad_token=None, sp_model_kwargs: Optional[Dict[str, Any]] = None, add_bos_token=True, add_eos_token=False, clean_up_tokenization_spaces=False, add_prefix_space=False, legacy=None, use_default_system_prompt=False, chat_template=None, **kwargs, ): self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token # Legacy behavior handling if legacy is None: logger.warning_once( f"You are using the default legacy behaviour of the {self.__class__.__name__}. This is" " expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you." " If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it" " means, and thoroughly read the reason why this was added as explained in" " https://github.com/huggingface/transformers/pull/24565" ) legacy = True self.legacy = legacy self.vocab_file = vocab_file self.add_bos_token = add_bos_token self.add_eos_token = add_eos_token self.add_prefix_space = add_prefix_space self.use_default_system_prompt = use_default_system_prompt self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(vocab_file)
super().__init__( bos_token=bos_token, eos_token=eos_token, unk_token=unk_token, pad_token=pad_token, add_bos_token=add_bos_token, add_eos_token=add_eos_token, sp_model_kwargs=self.sp_model_kwargs, clean_up_tokenization_spaces=clean_up_tokenization_spaces, add_prefix_space=add_prefix_space, legacy=legacy, use_default_system_prompt=use_default_system_prompt, chat_template=chat_template, **kwargs, )
def __getstate__(self): state = self.__dict__.copy() state["sp_model"] = None return state
def __setstate__(self, d): self.__dict__ = d self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file)
@property def vocab_size(self) -> int: """Returns the vocabulary size.""" return self.sp_model.get_piece_size()
def get_vocab(self) -> Dict[str, int]: """Returns the vocabulary as a dictionary of token to index.""" vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab
def _tokenize(self, text: str) -> List[str]: """ Tokenize a string. Args: text (`str`): The text to tokenize. Returns: `List[str]`: The list of tokens. """ if self.add_prefix_space: text = " " + text if self.legacy: return self.sp_model.encode(text, out_type=str) # Non-legacy behavior: handle special tokens properly return self.sp_model.encode(text, out_type=str)
def _convert_token_to_id(self, token: str) -> int: """Converts a token (str) to an id using the vocab.""" return self.sp_model.piece_to_id(token)
def _convert_id_to_token(self, index: int) -> str: """Converts an index (integer) to a token (str) using the vocab.""" token = self.sp_model.IdToPiece(index) return token
def convert_tokens_to_string(self, tokens: List[str]) -> str: """ Converts a sequence of tokens (strings) to a single string. This method handles special tokens separately to ensure they are not decoded using the SentencePiece model. Args: tokens (`List[str]`): The list of tokens to convert. Returns: `str`: The decoded string. """ current_sub_tokens = [] out_string = "" prev_is_special = False for i, token in enumerate(tokens): # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special and i != 0: out_string += " " out_string += self.sp_model.decode(current_sub_tokens) + token prev_is_special = True current_sub_tokens = [] else: current_sub_tokens.append(token) prev_is_special = False out_string += self.sp_model.decode(current_sub_tokens) return out_string
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]: """ Save the vocabulary and special tokens file to a directory. Args: save_directory (`str`): The directory in which to save the vocabulary. filename_prefix (`str`, *optional*): An optional prefix to add to the named of the saved files. Returns: `Tuple(str)`: Paths to the files saved. """ if not os.path.isdir(save_directory): logger.error(f"Vocabulary path ({save_directory}) should be a directory") return out_vocab_file = os.path.join( save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file, out_vocab_file) elif not os.path.isfile(self.vocab_file): with open(out_vocab_file, "wb") as fi: content_spiece_model = self.sp_model.serialized_model_proto() fi.write(content_spiece_model)
return (out_vocab_file,)
def build_inputs_with_special_tokens( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: """ Build model inputs from a sequence or a pair of sequences for sequence classification tasks by concatenating and adding special tokens. An IQuestCoder sequence has the following format: - single sequence: `<s> X </s>` (if add_eos_token is True) or `<s> X` (default) - pair of sequences: `<s> A </s> <s> B </s>` (if add_eos_token is True) or `<s> A <s> B` (default) Args: token_ids_0 (`List[int]`): List of IDs to which the special tokens will be added. token_ids_1 (`List[int]`, *optional*): Optional second list of IDs for sequence pairs. Returns: `List[int]`: List of input IDs with the appropriate special tokens. """ bos_token_id = [self.bos_token_id] if self.add_bos_token else [] eos_token_id = [self.eos_token_id] if self.add_eos_token else []
output = bos_token_id + token_ids_0 + eos_token_id
if token_ids_1 is not None: output = output + bos_token_id + token_ids_1 + eos_token_id
return output
def get_special_tokens_mask( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False ) -> List[int]: """ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer `prepare_for_model` method. Args: token_ids_0 (`List[int]`): List of IDs. token_ids_1 (`List[int]`, *optional*): Optional second list of IDs for sequence pairs. already_has_special_tokens (`bool`, *optional*, defaults to `False`): Whether or not the token list is already formatted with special tokens for the model. Returns: `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token. """ if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True )
bos_token_id = [1] if self.add_bos_token else [] eos_token_id = [1] if self.add_eos_token else []
if token_ids_1 is None: return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id return ( bos_token_id + ([0] * len(token_ids_0)) + eos_token_id + bos_token_id + ([0] * len(token_ids_1)) + eos_token_id )
def create_token_type_ids_from_sequences( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: """ Create a mask from the two sequences passed to be used in a sequence-pair classification task. An IQuestCoder sequence pair mask has the following format: ``` 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 | first sequence | second sequence | ``` If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s). Args: token_ids_0 (`List[int]`): List of IDs. token_ids_1 (`List[int]`, *optional*): Optional second list of IDs for sequence pairs. Returns: `List[int]`: List of token type IDs according to the given sequence(s). """ bos_token_id = [self.bos_token_id] if self.add_bos_token else [] eos_token_id = [self.eos_token_id] if self.add_eos_token else []
output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
if token_ids_1 is not None: output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
return output
@property def default_chat_template(self) -> str: """ Returns the default chat template for IQuestCoder. This template formats conversations with system, user, and assistant roles. """ return DEFAULT_CHAT_TEMPLATE
def apply_chat_template( self, conversation: Union[List[Dict[str, str]], "Conversation"], chat_template: Optional[str] = None, add_generation_prompt: bool = False, tokenize: bool = True, padding: bool = False, truncation: bool = False, max_length: Optional[int] = None, return_tensors: Optional[str] = None, return_dict: bool = False, **tokenizer_kwargs, ): """ Apply a chat template to format a conversation. Args: conversation (`List[Dict[str, str]]` or `Conversation`): A list of dicts with "role" and "content" keys, representing the conversation history. chat_template (`str`, *optional*): A Jinja template to use for formatting. If not provided, the tokenizer's default will be used. add_generation_prompt (`bool`, *optional*, defaults to `False`): Whether to add a generation prompt at the end for the assistant to continue. tokenize (`bool`, *optional*, defaults to `True`): Whether to tokenize the output. If `False`, returns a string. padding (`bool`, *optional*, defaults to `False`): Whether to pad sequences. truncation (`bool`, *optional*, defaults to `False`): Whether to truncate sequences. max_length (`int`, *optional*): Maximum length of the output. return_tensors (`str`, *optional*): The type of tensors to return ("pt", "tf", "np", or None). return_dict (`bool`, *optional*, defaults to `False`): Whether to return a dictionary with additional information. **tokenizer_kwargs: Additional keyword arguments passed to the tokenizer. Returns: `Union[str, List[int], BatchEncoding]`: The formatted (and optionally tokenized) conversation. Example: ```python >>> tokenizer = IQuestCoderTokenizer.from_pretrained("path/to/model") >>> conversation = [ ... {"role": "system", "content": "You are a helpful assistant."}, ... {"role": "user", "content": "Hello!"}, ... {"role": "assistant", "content": "Hi there! How can I help you today?"}, ... {"role": "user", "content": "What's the weather like?"}, ... ] >>> tokenizer.apply_chat_template(conversation, add_generation_prompt=True, tokenize=False) '<|system|>\\nYou are a helpful assistant.\\n</|system|><|user|>\\nHello!\\n</|user|>...' ``` """ # Use parent class implementation with our template return super().apply_chat_template( conversation, chat_template=chat_template, add_generation_prompt=add_generation_prompt, tokenize=tokenize, padding=padding, truncation=truncation, max_length=max_length, return_tensors=return_tensors, return_dict=return_dict, **tokenizer_kwargs, )
# Try to import and create Fast tokenizer versiontry: from transformers import PreTrainedTokenizerFast from tokenizers import Tokenizer, decoders, models, normalizers, pre_tokenizers, processors class IQuestCoderTokenizerFast(PreTrainedTokenizerFast): """ Construct a "fast" IQuestCoder tokenizer (backed by HuggingFace's *tokenizers* library). This is a fast implementation of [`IQuestCoderTokenizer`] using the 🤗 Tokenizers library. Args: vocab_file (`str`, *optional*): Path to the vocabulary file (SentencePiece model). tokenizer_file (`str`, *optional*): Path to a tokenizer JSON file. unk_token (`str`, *optional*, defaults to `"<unk>"`): The unknown token. bos_token (`str`, *optional*, defaults to `"<s>"`): The beginning of sequence token. eos_token (`str`, *optional*, defaults to `"</s>"`): The end of sequence token. pad_token (`str`, *optional*): The token used for padding. add_bos_token (`bool`, *optional*, defaults to `True`): Whether to add a BOS token at the start of sequences. add_eos_token (`bool`, *optional*, defaults to `False`): Whether to add an EOS token at the end of sequences. add_prefix_space (`bool`, *optional*, defaults to `False`): Whether to add an initial space to the input. use_default_system_prompt (`bool`, *optional*, defaults to `False`): Whether to use the default system prompt. chat_template (`str`, *optional*): A Jinja template for formatting conversations. Example: ```python >>> from tokenization_iquestcoder import IQuestCoderTokenizerFast >>> tokenizer = IQuestCoderTokenizerFast.from_pretrained("path/to/model") >>> tokenizer.encode("Hello, world!") [1, 15043, 29892, 3186, 29991] ``` """ vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES model_input_names = ["input_ids", "attention_mask"] slow_tokenizer_class = IQuestCoderTokenizer def __init__( self, vocab_file=None, tokenizer_file=None, unk_token="<unk>", bos_token="<s>", eos_token="</s>", pad_token=None, add_bos_token=True, add_eos_token=False, add_prefix_space=False, use_default_system_prompt=False, chat_template=None, **kwargs, ): self.add_bos_token = add_bos_token self.add_eos_token = add_eos_token self.add_prefix_space = add_prefix_space self.use_default_system_prompt = use_default_system_prompt if chat_template is None: chat_template = DEFAULT_CHAT_TEMPLATE super().__init__( vocab_file=vocab_file, tokenizer_file=tokenizer_file, unk_token=unk_token, bos_token=bos_token, eos_token=eos_token, pad_token=pad_token, add_bos_token=add_bos_token, add_eos_token=add_eos_token, add_prefix_space=add_prefix_space, use_default_system_prompt=use_default_system_prompt, chat_template=chat_template, **kwargs, ) @property def can_save_slow_tokenizer(self) -> bool: return os.path.isfile(self.vocab_file) if self.vocab_file else False @property def default_chat_template(self) -> str: """Returns the default chat template.""" return DEFAULT_CHAT_TEMPLATE def build_inputs_with_special_tokens( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: """Build model inputs with special tokens.""" bos_token_id = [self.bos_token_id] if self.add_bos_token else [] eos_token_id = [self.eos_token_id] if self.add_eos_token else []
output = bos_token_id + token_ids_0 + eos_token_id
if token_ids_1 is not None: output = output + bos_token_id + token_ids_1 + eos_token_id
return output def get_special_tokens_mask( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False ) -> List[int]: """Retrieve special tokens mask.""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True )
bos_token_id = [1] if self.add_bos_token else [] eos_token_id = [1] if self.add_eos_token else []
if token_ids_1 is None: return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id return ( bos_token_id + ([0] * len(token_ids_0)) + eos_token_id + bos_token_id + ([0] * len(token_ids_1)) + eos_token_id ) def create_token_type_ids_from_sequences( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: """Create token type IDs from sequences.""" bos_token_id = [self.bos_token_id] if self.add_bos_token else [] eos_token_id = [self.eos_token_id] if self.add_eos_token else []
output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
if token_ids_1 is not None: output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
return output
except ImportError: # tokenizers library not available, Fast tokenizer not supported IQuestCoderTokenizerFast = None logger.info( "The `tokenizers` library is not installed. " "IQuestCoderTokenizerFast will not be available. " "Install it with `pip install tokenizers`." )
123version https://git-lfs.github.com/spec/v1oid sha256:7d3be68e090a927f31e0e378d7599b15c206dd47e4a73933775a746cc9c1cd91size 1345108123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241{ "add_bos_token": false, "add_eos_token": false, "added_tokens_decoder": { "0": { "content": "<unk>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": true, "special": true }, "1": { "content": "<s>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": true }, "2": { "content": "</s>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": true, "special": true }, "75858": { "content": "<CLS>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "75859": { "content": "<SEP>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "75860": { "content": "<EOD>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "75861": { "content": "<MASK>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "75862": { "content": "<PAD>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "75863": { "content": "<|im_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "75864": { "content": "<|im_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "75865": { "content": "<|fim_prefix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "75866": { "content": "<|fim_middle|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "75867": { "content": "<|fim_suffix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "75868": { "content": "<|fim_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "75869": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "75870": { "content": "<|repo_name|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "75871": { "content": "<|file_sep|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "75872": { "content": "<think>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "75873": { "content": "</think>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "75874": { "content": "<tools>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "75875": { "content": "</tools>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "75876": { "content": "<tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "75877": { "content": "</tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "75878": { "content": "<tool_response>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "75879": { "content": "</tool_response>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false } }, "additional_special_tokens": [ "<|CLS|>", "<|SEP|>", "<|EOD|>", "<|MASK|>", "<|PAD|>", "<|fim_prefix|>", "<|fim_middle|>", "<|fim_suffix|>", "<|im_start|>", "<|im_end|>", "<|fim_pad|>", "<|endoftext|>", "<|repo_name|>", "<|file_sep|>", "<think>", "</think>" ], "auto_map": { "AutoTokenizer": [ "tokenization_iquestcoder.IQuestCoderTokenizer", null ] }, "bos_token": "<s>", "chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0].role == 'system' %}\n {{- messages[0].content + '\\n\\n' }}\n {%- else %}\n {{- 'You are IQuest-Coder, a helpful assistant developed by IQuest.' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou have access to the following functions:\\n\\n<tools>\" }}\n {%- for tool in tools %}\n {%- if tool.type == 'function' and tool.function %}\n {%- set func = tool.function %}\n {%- else %}\n {%- set func = tool %}\n {%- endif %}\n {{- \"\\n<function>\\n<name>\" + func.name + \"</name>\" }}\n {%- if func.description %}\n {{- \"\\n<description>\" + func.description + \"</description>\" }}\n {%- endif %}\n {{- \"\\n<parameters>\" }}\n {%- if func.parameters and func.parameters.properties %}\n {%- for param_name, param_fields in func.parameters.properties.items() %}\n {{- \"\\n<parameter>\" }}\n {{- \"\\n<name>\" + param_name + \"</name>\" }}\n {%- if param_fields.type %}\n {{- \"\\n<type>\" + param_fields.type + \"</type>\" }}\n {%- endif %}\n {%- if param_fields.description %}\n {{- \"\\n<description>\" + param_fields.description + \"</description>\" }}\n {%- endif %}\n {{- \"\\n</parameter>\" }}\n {%- endfor %}\n {%- endif %}\n {{- \"\\n</parameters>\\n</function>\" }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nIf you choose to call a function ONLY reply in the following format:\\n\\n<tool_call>\\n<function=example_function_name>\\n<parameter=example_parameter_1>\\nvalue_1\\n</parameter>\\n</function>\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0].role == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0].content + '<|im_end|>\\n' }}\n {%- else %}\n {{- '<|im_start|>system\\nYou are IQuest-Coder, a helpful assistant developed by IQuest.<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set content = message.content %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- if message.tool_calls %}\n {%- for tool_call in message.tool_calls %}\n {%- if (loop.first and content) or (not loop.first) %}\n {{- '\\n' }}\n {%- endif %}\n {%- if tool_call.function %}\n {%- set tc = tool_call.function %}\n {%- else %}\n {%- set tc = tool_call %}\n {%- endif %}\n {{- '<tool_call>\\n<function=' + tc.name + '>\\n' }}\n {%- if tc.arguments is string %}\n {%- set args = tc.arguments | fromjson %}\n {%- else %}\n {%- set args = tc.arguments %}\n {%- endif %}\n {%- for arg_name, arg_value in args.items() %}\n {{- '<parameter=' + arg_name + '>\\n' }}\n {%- if arg_value is string %}\n {{- arg_value }}\n {%- else %}\n {{- arg_value | tojson }}\n {%- endif %}\n {{- '\\n</parameter>\\n' }}\n {%- endfor %}\n {{- '</function>\\n</tool_call>' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.first or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n{%- endif %}", "clean_up_tokenization_spaces": false, "eos_token": "<|im_end|>", "model_max_length": 131072, "pad_token": "<|endoftext|>", "padding_side": "right", "sp_model_kwargs": {}, "split_special_tokens": false, "tokenizer_class": "IQuestCoderTokenizer", "unk_token": "<unk>", "use_fast": false}.gitattributes+2
LICENSE+26
README.md+260-5
config.jsonAdded+41
configuration_iquestcoder.pyAdded+182
generation_config.jsonAdded+6
model-00001-of-00003.safetensorsAdded+3
model-00002-of-00003.safetensorsAdded+3
model-00003-of-00003.safetensorsAdded+3
model.safetensors.index.jsonAdded+136
modeling_iquestcoder.pyAdded+1068
papers/iquest-coder-v1-logo.pngAdded

Large File Pointer Details
- SHA256: 2fad84bb195ec8628191705c8c3f21ec21dc6dee27b72884e5342b3ffa0a0c0f
- Pointer size: 131 Bytes
- Size of remote file: 123 kB
papers/results.pngAdded

Large File Pointer Details
- SHA256: b4b14ddc9c3fdfa2eed779e393a4ed67754255863b5d7f62641a4a04fcf2d462
- Pointer size: 131 Bytes
- Size of remote file: 453 kB
tokenization_iquestcoder.pyAdded+552
tokenizer.jsonAdded
tokenizer.modelAdded+3
tokenizer_config.jsonAdded+241