Run this model with HF Jobs
Run mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Instructions to use mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit with MLX:
# Make sure mlx-lm is installed # pip install --upgrade mlx-lm # Generate text with mlx-lm from mlx_lm import load, generate model, tokenizer = load("mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit") prompt = "Write a story about Einstein" messages = [{"role": "user", "content": prompt}] prompt = tokenizer.apply_chat_template( messages, add_generation_prompt=True ) text = generate(model, tokenizer, prompt=prompt, verbose=True) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- Pi
How to use mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit with Pi:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit"
Configure the model in Pi
# Install Pi: npm install -g @earendil-works/pi-coding-agent # Add to ~/.pi/agent/models.json: { "providers": { "mlx-lm": { "baseUrl": "http://localhost:8080/v1", "api": "openai-completions", "apiKey": "none", "models": [ { "id": "mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit" } ] } } }Run Pi
# Start Pi in your project directory: pi
- MLX LM
How to use mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit with MLX LM:
Generate or start a chat session
# Install MLX LM uv tool install mlx-lm # Interactive chat REPL mlx_lm.chat --model "mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit"
Run an OpenAI-compatible server
# Install MLX LM uv tool install mlx-lm # Start the server mlx_lm.server --model "mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit" # Calling the OpenAI-compatible server with curl curl -X POST "http://localhost:8080/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit", "messages": [ {"role": "user", "content": "Hello"} ] }' - Hermes Agent
How to use mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit with Hermes Agent:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit"
Configure Hermes
# Install Hermes: curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash hermes setup # Point Hermes at the local server: hermes config set model.provider custom hermes config set model.base_url http://127.0.0.1:8080/v1 hermes config set model.default mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit
Run Hermes
hermes
- Atomic Chat
- OpenClaw
How to use mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit with OpenClaw:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit"
Configure OpenClaw
# Install OpenClaw: npm install -g openclaw@latest # Register the local server and set it as the default model: openclaw onboard --non-interactive --mode local \ --auth-choice custom-api-key \ --custom-base-url http://127.0.0.1:8080/v1 \ --custom-model-id "mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit" \ --custom-provider-id mlx-lm \ --custom-compatibility openai \ --custom-text-input \ --accept-risk \ --skip-health
Run OpenClaw
openclaw agent --local --agent main --message "Hello from Hugging Face"
Add files using upload-large-folder tool
Browse filesFiles changed (20)
- README.mdAdded+40
- __init__.pyAdded+26
- added_tokens.jsonAdded+29
- chat_template.jinjaAdded+69
- config.jsonAdded+47
- configuration_iquestloopcoder.pyAdded+132
- generation_config.jsonAdded+6
- model-00001-of-00007.safetensorsAdded+3
- model-00002-of-00007.safetensorsAdded+3
- model-00003-of-00007.safetensorsAdded+3
- model-00004-of-00007.safetensorsAdded+3
- model-00005-of-00007.safetensorsAdded+3
- model-00006-of-00007.safetensorsAdded+3
- model-00007-of-00007.safetensorsAdded+3
- model.safetensors.index.jsonAdded
- modeling_iquestloopcoder.pyAdded+1421
- special_tokens_map.jsonAdded+48
- tokenization_iquestcoder.pyAdded+552
- tokenizer.modelAdded+3
- tokenizer_config.jsonAdded+285
12345678910111213141516171819202122232425262728293031323334353637383940---license: otherlicense_name: iquestcoderlicense_link: https://huggingface.co/IQuestLab/IQuest-Coder-V1-40B-Instruct/blob/main/LICENSElanguage:- enlibrary_name: mlxpipeline_tag: text-generationtags:- mlxbase_model: IQuestLab/IQuest-Coder-V1-40B-Loop-Instruct---
# mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit
This model [mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit](https://huggingface.co/mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit) wasconverted to MLX format from [IQuestLab/IQuest-Coder-V1-40B-Loop-Instruct](https://huggingface.co/IQuestLab/IQuest-Coder-V1-40B-Loop-Instruct)using mlx-lm version **0.30.0**.
## Use with mlx
```bashpip install mlx-lm```
```pythonfrom mlx_lm import load, generate
model, tokenizer = load("mlx-community/IQuest-Coder-V1-40B-Loop-Instruct-6bit")
prompt = "hello"
if tokenizer.chat_template is not None: messages = [{"role": "user", "content": prompt}] prompt = tokenizer.apply_chat_template( messages, add_generation_prompt=True, return_dict=False, )
response = generate(model, tokenizer, prompt=prompt, verbose=True)```1234567891011121314151617181920212223242526"""IQuestLoopCoder model package."""
from .configuration_iquestloopcoder import IQuestLoopCoderConfigfrom .modeling_iquestloopcoder import ( IQuestLoopCoderPreTrainedModel, IQuestLoopCoderModel, IQuestLoopCoderForCausalLM, IQuestLoopCoderCache,)from .tokenization_iquestcoder import IQuestCoderTokenizer
try: from .tokenization_iquestcoder import IQuestCoderTokenizerFastexcept ImportError: IQuestCoderTokenizerFast = None
__all__ = [ "IQuestLoopCoderConfig", "IQuestLoopCoderPreTrainedModel", "IQuestLoopCoderModel", "IQuestLoopCoderForCausalLM", "IQuestLoopCoderCache", "IQuestCoderTokenizer", "IQuestCoderTokenizerFast",]
1234567891011121314151617181920212223242526272829{ "</think>": 75873, "</tool_call>": 75877, "</tool_response>": 75879, "</tools>": 75875, "<CLS>": 75858, "<EOD>": 75860, "<MASK>": 75861, "<PAD>": 75862, "<SEP>": 75859, "<think>": 75872, "<tool_call>": 75876, "<tool_response>": 75878, "<tools>": 75874, "<|CLS|>": 75880, "<|EOD|>": 75882, "<|MASK|>": 75883, "<|PAD|>": 75884, "<|SEP|>": 75881, "<|endoftext|>": 75869, "<|file_sep|>": 75871, "<|fim_middle|>": 75866, "<|fim_pad|>": 75868, "<|fim_prefix|>": 75865, "<|fim_suffix|>": 75867, "<|im_end|>": 75864, "<|im_start|>": 75863, "<|repo_name|>": 75870}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869{%- if tools %} {{- '<|im_start|>system\n' }} {%- if messages[0].role == 'system' %} {{- messages[0].content + '\n\n' }} {%- else %} {{- 'You are LoopCoder, a helpful assistant developed by IQuest.' }} {%- endif %} {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }} {%- for tool in tools %} {{- "\n" }} {{- tool | tojson }} {%- endfor %} {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}{%- else %} {%- if messages[0].role == 'system' %} {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }} {%- else %} {{- '<|im_start|>system\nYou are LoopCoder, a helpful assistant developed by IQuest.<|im_end|>\n' }} {%- endif %}{%- endif %}{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}{%- for message in messages[::-1] %} {%- set index = (messages|length - 1) - loop.index0 %} {%- if ns.multi_step_tool and message.role == "user" and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %} {%- set ns.multi_step_tool = false %} {%- set ns.last_query_index = index %} {%- endif %}{%- endfor %}{%- for message in messages %} {%- if (message.role == "user") or (message.role == "system" and not loop.first) %} {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }} {%- elif message.role == "assistant" %} {%- set content = message.content %} {{- '<|im_start|>' + message.role + '\n' + content }} {%- if message.tool_calls %} {%- for tool_call in message.tool_calls %} {%- if (loop.first and content) or (not loop.first) %} {{- '\n' }} {%- endif %} {%- if tool_call.function %} {%- set tool_call = tool_call.function %} {%- endif %} {{- '<tool_call>\n{"name": "' }} {{- tool_call.name }} {{- '", "arguments": ' }} {%- if tool_call.arguments is string %} {{- tool_call.arguments }} {%- else %} {{- tool_call.arguments | tojson }} {%- endif %} {{- '}\n</tool_call>' }} {%- endfor %} {%- endif %} {{- '<|im_end|>\n' }} {%- elif message.role == "tool" %} {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} {{- '<|im_start|>user' }} {%- endif %} {{- '\n<tool_response>\n' }} {{- message.content }} {{- '\n</tool_response>' }} {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} {{- '<|im_end|>\n' }} {%- endif %} {%- endif %}{%- endfor %}{%- if add_generation_prompt %} {{- '<|im_start|>assistant\n' }}{%- endif %}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647{ "architectures": [ "IQuestLoopCoderForCausalLM" ], "attention_bias": false, "attention_dropout": 0.0, "auto_map": { "AutoConfig": "configuration_iquestloopcoder.IQuestLoopCoderConfig", "AutoModel": "modeling_iquestloopcoder.IQuestLoopCoderModel", "AutoModelForCausalLM": "modeling_iquestloopcoder.IQuestLoopCoderForCausalLM" }, "eos_token_id": [ 2, 75864, 75869 ], "head_dim": 128, "hidden_act": "silu", "hidden_size": 5120, "initializer_range": 0.02, "intermediate_size": 27648, "loop_num": 2, "loop_window_size": 64, "max_position_embeddings": 131072, "mlp_bias": false, "model_type": "iquestloopcoder", "num_attention_heads": 40, "num_hidden_layers": 80, "num_key_value_heads": 8, "quantization": { "group_size": 64, "bits": 6, "mode": "affine" }, "quantization_config": { "group_size": 64, "bits": 6, "mode": "affine" }, "rms_norm_eps": 1e-05, "rope_theta": 500000, "tie_word_embeddings": false, "torch_dtype": "bfloat16", "transformers_version": "4.40.0", "use_cache": true, "vocab_size": 76800}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132# Copyright 2024 IQuestLoopCoder Authors## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License."""IQuestLoopCoder model configuration"""
from transformers.configuration_utils import PretrainedConfigfrom transformers.utils import logging
logger = logging.get_logger(__name__)
class IQuestLoopCoderConfig(PretrainedConfig): r""" Configuration class for IQuestLoopCoder model. IQuestLoopCoder extends the standard LLaMA architecture with a loop mechanism: - Loop 1: Standard attention, stores K1, V1 - Loop 2+: Mixed attention with gated combination of global (K1,V1) and local (K2,V2) KV The gate is computed as: gate = sigmoid(W @ Q + bias) Mixed output = gate * Attention(Q, K1, V1) + (1 - gate) * SlidingWindowAttention(Q, K2, V2) Args: vocab_size (`int`, *optional*, defaults to 76800): Vocabulary size of the model. hidden_size (`int`, *optional*, defaults to 5120): Dimension of the hidden representations. intermediate_size (`int`, *optional*, defaults to 27648): Dimension of the MLP representations (FFN hidden size). 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. num_key_value_heads (`int`, *optional*, defaults to 8): Number of key-value heads (for GQA). If None, defaults to num_attention_heads. head_dim (`int`, *optional*, defaults to 128): Dimension of each attention head (hidden_size // num_attention_heads). hidden_act (`str` or `function`, *optional*, defaults to `"silu"`): Activation function in the MLP. max_position_embeddings (`int`, *optional*, defaults to 8192): Maximum sequence length. initializer_range (`float`, *optional*, defaults to 0.02): Standard deviation for weight initialization. rms_norm_eps (`float`, *optional*, defaults to 1e-5): Epsilon for RMS normalization layers. use_cache (`bool`, *optional*, defaults to `True`): Whether to use past key/values for generation. tie_word_embeddings (`bool`, *optional*, defaults to `False`): Whether to tie input and output embeddings. rope_theta (`float`, *optional*, defaults to 500000.0): Base value for rotary position embeddings. attention_bias (`bool`, *optional*, defaults to `False`): Whether to use bias in attention layers. attention_dropout (`float`, *optional*, defaults to 0.0): Dropout ratio for attention weights. mlp_bias (`bool`, *optional*, defaults to `False`): Whether to use bias in MLP layers. # Loop-specific parameters loop_num (`int`, *optional*, defaults to 2): Number of loops through the decoder. loop_window_size (`int`, *optional*, defaults to 64): Window size for sliding window attention in Loop 2+. """ model_type = "iquestloopcoder" 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=8192, 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, # Loop-specific parameters loop_num=2, loop_window_size=64, **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.head_dim = head_dim # GQA support if num_key_value_heads is None: num_key_value_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads 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 # Loop-specific self.loop_num = loop_num self.loop_window_size = loop_window_size
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, )
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:b0d2a1a36c82f31c40649b09fcb44b51d7bbf876e843226b6605f59e7eaa7fc0size 5354898455123version https://git-lfs.github.com/spec/v1oid sha256:2030e21aabc97dbda1a182af9730cc89393f83ff558457e7e81e32893d873d75size 5316603256123version https://git-lfs.github.com/spec/v1oid sha256:9c7ce0d881c79dc6133408b600b6ca298ae784b6abe71f055daa5ba5810ad33asize 5265463145123version https://git-lfs.github.com/spec/v1oid sha256:826c41bb3f288f75ca370cfcb448ef1407e7f43e2fbc4ec2263ee7956b962652size 5265463111123version https://git-lfs.github.com/spec/v1oid sha256:c1f87174a4a415e9acbe7e8c8e77096b878a0e53748532084aecc23570a111fdsize 5316603232123version https://git-lfs.github.com/spec/v1oid sha256:948f43fd76e914d41634c2941b0b1ed84ef25a7ff41d9a2318423fadaed4fc13size 5265463097123version https://git-lfs.github.com/spec/v1oid sha256:b0ebc7dc09115db46f65c3a7ecf2323219f96388f85f6db2d2329f7e7a8a955dsize 55039342312345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421"""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."""
import mathfrom typing import Any, List, Optional, Tuple, Union
import torchimport torch.nn.functional as Fimport torch.utils.checkpointfrom torch import nn
from transformers.activations import ACT2FNfrom transformers.cache_utils import Cache, DynamicCache, StaticCachefrom transformers.modeling_attn_mask_utils import AttentionMaskConverterfrom transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast,)from transformers.modeling_utils import PreTrainedModelfrom transformers.generation.utils import GenerationMixinfrom transformers.utils import ( add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings,)
from .configuration_iquestloopcoder import IQuestLoopCoderConfig
logger = logging.get_logger(__name__)
_CONFIG_FOR_DOC = "IQuestLoopCoderConfig"
class IQuestLoopCoderCache(Cache): """Cache implementation for IQuestLoopCoder that manages shared and local KV caches. - shared_key_cache/shared_value_cache: Stores KV from Loop 1 (global context) - local_key_cache/local_value_cache: Stores KV from Loop 2+ (local window, only window_size tokens) """ def __init__(self, window_size: int, num_layers: int): # We intentionally don't call super().__init__ because the parent assumes static cache sizes. self.window_size = window_size self.num_layers = num_layers # Shared cache: stores Loop 1 KV (global context) self.shared_key_cache: List[Optional[torch.Tensor]] = [None] * num_layers self.shared_value_cache: List[Optional[torch.Tensor]] = [None] * num_layers # Local cache: stores Loop 2+ KV (sliding window, only window_size tokens) self.local_key_cache: List[Optional[torch.Tensor]] = [None] * num_layers self.local_value_cache: List[Optional[torch.Tensor]] = [None] * num_layers self.layers: List[Any] = [] # attribute expected by HF Cache utilities self._seen_tokens = 0 def update_shared( self, key_states: torch.Tensor, value_states: torch.Tensor, layer_idx: int, cache_kwargs: Optional[dict] = None, ) -> Tuple[torch.Tensor, torch.Tensor]: """Update shared cache (Loop 1 KV).""" if layer_idx < 0 or layer_idx >= self.num_layers: raise ValueError(f"layer_idx must be in [0, {self.num_layers}), got {layer_idx}") cached_key = self.shared_key_cache[layer_idx] cached_value = self.shared_value_cache[layer_idx] if cached_key is None: self.shared_key_cache[layer_idx] = key_states self.shared_value_cache[layer_idx] = value_states else: if ( key_states.shape[0] != cached_key.shape[0] or key_states.shape[1] != cached_key.shape[1] or key_states.shape[3] != cached_key.shape[3] ): raise ValueError( "Cached and incoming key/value tensors must match on batch, head, and head_dim dimensions." ) assert cached_value is not None self.shared_key_cache[layer_idx] = torch.cat([cached_key, key_states], dim=2) self.shared_value_cache[layer_idx] = torch.cat([cached_value, value_states], dim=2) result_key = self.shared_key_cache[layer_idx] result_value = self.shared_value_cache[layer_idx] assert result_key is not None and result_value is not None # Track sequence length self._seen_tokens = result_key.shape[2] return result_key, result_value def update_local( self, key_states: torch.Tensor, value_states: torch.Tensor, layer_idx: int, cache_kwargs: Optional[dict] = None, ) -> Tuple[torch.Tensor, torch.Tensor]: """Update local cache (Loop 2+ KV) with sliding window management. If the cache is full (window_size tokens), remove the oldest token and add the new one. """ if layer_idx < 0 or layer_idx >= self.num_layers: raise ValueError(f"layer_idx must be in [0, {self.num_layers}), got {layer_idx}") cached_key = self.local_key_cache[layer_idx] cached_value = self.local_value_cache[layer_idx] if cached_key is None: # First token in local cache self.local_key_cache[layer_idx] = key_states self.local_value_cache[layer_idx] = value_states else: if ( key_states.shape[0] != cached_key.shape[0] or key_states.shape[1] != cached_key.shape[1] or key_states.shape[3] != cached_key.shape[3] ): raise ValueError( "Cached and incoming key/value tensors must match on batch, head, and head_dim dimensions." ) assert cached_value is not None # Check if we need to remove the oldest token current_len = cached_key.shape[2] if current_len >= self.window_size: # Remove the first token (oldest) and add the new one self.local_key_cache[layer_idx] = torch.cat([cached_key[:, :, 1:, :], key_states], dim=2) self.local_value_cache[layer_idx] = torch.cat([cached_value[:, :, 1:, :], value_states], dim=2) else: # Just append self.local_key_cache[layer_idx] = torch.cat([cached_key, key_states], dim=2) self.local_value_cache[layer_idx] = torch.cat([cached_value, value_states], dim=2) result_key = self.local_key_cache[layer_idx] result_value = self.local_value_cache[layer_idx] assert result_key is not None and result_value is not None return result_key, result_value def get_shared(self, layer_idx: int) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor]]: """Get shared cache for a layer.""" if layer_idx < 0 or layer_idx >= self.num_layers: return None, None return self.shared_key_cache[layer_idx], self.shared_value_cache[layer_idx] def get_local(self, layer_idx: int) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor]]: """Get local cache for a layer.""" if layer_idx < 0 or layer_idx >= self.num_layers: return None, None return self.local_key_cache[layer_idx], self.local_value_cache[layer_idx] def update( self, key_states: torch.Tensor, value_states: torch.Tensor, layer_idx: int, cache_kwargs: Optional[dict] = None, ) -> Tuple[torch.Tensor, torch.Tensor]: """Default update method (for compatibility, updates shared cache).""" return self.update_shared(key_states, value_states, layer_idx, cache_kwargs) def get_seq_length(self, layer_idx: Optional[int] = 0) -> int: """Get sequence length from shared cache.""" if layer_idx is None: layer_idx = 0 if layer_idx < 0 or layer_idx >= len(self.shared_key_cache): return 0 cached = self.shared_key_cache[layer_idx] if cached is None: return 0 return cached.shape[2] def get_max_length(self) -> Optional[int]: return None def get_usable_length( self, new_seq_length: int, layer_idx: Optional[int] = 0 ) -> int: return self.get_seq_length(layer_idx) def reorder_cache(self, beam_idx: torch.LongTensor) -> None: """Reorder cache for beam search.""" for layer_idx in range(self.num_layers): if self.shared_key_cache[layer_idx] is not None: device = self.shared_key_cache[layer_idx].device self.shared_key_cache[layer_idx] = self.shared_key_cache[layer_idx].index_select(0, beam_idx.to(device)) self.shared_value_cache[layer_idx] = self.shared_value_cache[layer_idx].index_select(0, beam_idx.to(device)) if self.local_key_cache[layer_idx] is not None: device = self.local_key_cache[layer_idx].device self.local_key_cache[layer_idx] = self.local_key_cache[layer_idx].index_select(0, beam_idx.to(device)) self.local_value_cache[layer_idx] = self.local_value_cache[layer_idx].index_select(0, beam_idx.to(device)) @property def is_compileable(self) -> bool: return False def clear(self) -> None: """Clear all caches.""" logger.debug("Clearing IQuestLoopCoderCache") self.shared_key_cache = [None] * self.num_layers self.shared_value_cache = [None] * self.num_layers self.local_key_cache = [None] * self.num_layers self.local_value_cache = [None] * self.num_layers self._seen_tokens = 0
class IQuestLoopCoderRMSNorm(nn.Module): """RMS Normalization layer.""" def __init__(self, hidden_size, eps=1e-6): super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps
def forward(self, hidden_states): 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)
class IQuestLoopCoderRotaryEmbedding(nn.Module): """Rotary Position Embedding (RoPE).""" def __init__(self, dim, max_position_embeddings=8192, base=500000.0, device=None, scaling_factor=1.0): super().__init__() self.scaling_factor = scaling_factor self.dim = dim self.max_position_embeddings = max_position_embeddings self.base = base inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim)) self.register_buffer("inv_freq", inv_freq, persistent=False) self.max_seq_len_cached = max_position_embeddings
@torch.no_grad() def forward(self, x, position_ids): # x: [batch_size, num_heads, seq_len, head_dim] inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1) position_ids_expanded = position_ids[:, None, :].float() device_type = x.device.type 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() sin = emb.sin() return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
def rotate_half(x): """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, k, cos, sin, position_ids=None, unsqueeze_dim=1): """Applies Rotary Position Embedding to the query and key tensors.""" 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, k_embed
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """Expand KV heads to match query heads for GQA.""" 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)
class IQuestLoopCoderMLP(nn.Module): """MLP with SwiGLU activation.""" def __init__(self, config): 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): return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
class LoopGateProjection(nn.Module): """Gate projection for mixed attention in Loop 2+. Computes: g = sigmoid(linear(Q)) for each head independently. This gate determines how much to use Loop1's KV (global) vs current loop's KV (local). """ def __init__(self, num_heads: int, head_dim: int): super().__init__() self.num_heads = num_heads self.head_dim = head_dim # Each head has its own gate: Linear(head_dim -> 1) per head # Implemented as [num_heads, head_dim] weight + [num_heads] bias self.weight = nn.Parameter(torch.zeros(num_heads, head_dim)) self.bias = nn.Parameter(torch.zeros(num_heads)) def forward(self, query: torch.Tensor) -> torch.Tensor: """Compute gate values from query tensor. Args: query: [batch, num_heads, seq_len, head_dim] Returns: gate: [batch, num_heads, seq_len, 1] """ # query: [batch, num_heads, seq_len, head_dim] # weight: [num_heads, head_dim] # For each head h: gate_h = query[:, h, :, :] @ weight[h, :].T + bias[h] # Using einsum: gate = einsum('bhsd,hd->bhs', query, weight) + bias gate_logits = torch.einsum('bhsd,hd->bhs', query, self.weight) # [batch, num_heads, seq_len] gate_logits = gate_logits + self.bias[None, :, None] # broadcast bias gate = torch.sigmoid(gate_logits) return gate.unsqueeze(-1) # [batch, num_heads, seq_len, 1]
class IQuestLoopCoderAttention(nn.Module): """Multi-head attention with GQA support.""" def __init__(self, config: IQuestLoopCoderConfig, layer_idx: Optional[int] = None): super().__init__() self.config = config self.layer_idx = layer_idx self.hidden_size = config.hidden_size self.num_heads = config.num_attention_heads self.head_dim = config.head_dim self.num_key_value_heads = config.num_key_value_heads self.num_key_value_groups = self.num_heads // self.num_key_value_heads self.max_position_embeddings = config.max_position_embeddings self.rope_theta = config.rope_theta self.attention_dropout = config.attention_dropout self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias) self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias) self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias) self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias) self.rotary_emb = IQuestLoopCoderRotaryEmbedding( self.head_dim, max_position_embeddings=self.max_position_embeddings, base=self.rope_theta, )
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: bool = False, use_cache: bool = False, cache_position: Optional[torch.LongTensor] = None, **kwargs, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: bsz, q_len, _ = hidden_states.size()
query_states = self.q_proj(hidden_states) key_states = self.k_proj(hidden_states) value_states = self.v_proj(hidden_states)
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
cos, sin = self.rotary_emb(value_states, position_ids) query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
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)
# Repeat KV for GQA key_states = repeat_kv(key_states, self.num_key_value_groups) value_states = repeat_kv(value_states, self.num_key_value_groups)
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
if attention_mask is not None: causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] attn_weights = attn_weights + causal_mask
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype) attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training) attn_output = torch.matmul(attn_weights, value_states)
attn_output = attn_output.transpose(1, 2).contiguous() attn_output = attn_output.reshape(bsz, q_len, -1) attn_output = self.o_proj(attn_output)
return attn_output, attn_weights if output_attentions else None, past_key_value def forward_with_external_kv( self, hidden_states: torch.Tensor, external_key: torch.Tensor, external_value: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, sliding_window: Optional[int] = None, ) -> torch.Tensor: """Forward pass using external K, V (for Loop 2+ mixed attention). Args: hidden_states: Input for computing Q external_key: Pre-computed K (already with RoPE applied) external_value: Pre-computed V attention_mask: Causal attention mask position_ids: Position IDs sliding_window: If set, apply sliding window attention Returns: Attention output [batch, seq_len, num_heads, head_dim] """ bsz, q_len, _ = hidden_states.size() # Compute Q from current hidden states query_states = self.q_proj(hidden_states) query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) # Apply RoPE to Q cos, sin = self.rotary_emb(query_states, position_ids) query_states = (query_states * cos.unsqueeze(1)) + (rotate_half(query_states) * sin.unsqueeze(1)) # Use external K, V (already have RoPE for K) key_states = external_key value_states = external_value # Repeat KV for GQA key_states = repeat_kv(key_states, self.num_key_value_groups) value_states = repeat_kv(value_states, self.num_key_value_groups) # Compute attention attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) # Apply attention mask (causal) if attention_mask is not None: causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] attn_weights = attn_weights + causal_mask # Apply sliding window mask if needed if sliding_window is not None and q_len > sliding_window: # Create sliding window mask # For each position i, can only attend to [i-window+1, i] seq_len = key_states.shape[2] row_idx = torch.arange(q_len, device=query_states.device).unsqueeze(1) col_idx = torch.arange(seq_len, device=query_states.device).unsqueeze(0) window_mask = (col_idx > row_idx) | (col_idx < row_idx - sliding_window + 1) window_mask = window_mask.unsqueeze(0).unsqueeze(0) # [1, 1, q_len, seq_len] attn_weights = attn_weights.masked_fill(window_mask, float('-inf')) attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype) attn_output = torch.matmul(attn_weights, value_states) # Don't apply o_proj here - return raw attention output attn_output = attn_output.transpose(1, 2).contiguous() return attn_output # [batch, seq_len, num_heads, head_dim] def get_qkv( self, hidden_states: torch.Tensor, position_ids: Optional[torch.LongTensor] = None, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Get Q, K, V tensors with RoPE applied. Returns: query: [batch, num_heads, seq_len, head_dim] key: [batch, num_kv_heads, seq_len, head_dim] value: [batch, num_kv_heads, seq_len, head_dim] """ bsz, q_len, _ = hidden_states.size() query_states = self.q_proj(hidden_states) key_states = self.k_proj(hidden_states) value_states = self.v_proj(hidden_states) query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) cos, sin = self.rotary_emb(value_states, position_ids) query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) return query_states, key_states, value_states def forward_decode_loop1( self, hidden_states: torch.Tensor, past_shared_key: Optional[torch.Tensor], past_shared_value: Optional[torch.Tensor], attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, cache_position: Optional[torch.LongTensor] = None, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Forward pass for Loop 1 in decode stage. Args: hidden_states: Current hidden states [batch, 1, hidden_size] past_shared_key: Past shared keys from cache [batch, num_kv_heads, past_len, head_dim] past_shared_value: Past shared values from cache [batch, num_kv_heads, past_len, head_dim] attention_mask: Causal attention mask position_ids: Position IDs cache_position: Cache position Returns: output: Attention output [batch, 1, hidden_size] k1: Current key [batch, num_kv_heads, 1, head_dim] (only current token) v1: Current value [batch, num_kv_heads, 1, head_dim] (only current token) """ bsz, q_len, _ = hidden_states.size() query_states = self.q_proj(hidden_states) key_states = self.k_proj(hidden_states) value_states = self.v_proj(hidden_states) query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) cos, sin = self.rotary_emb(value_states, position_ids) query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) # Store current token's k1, v1 for return (before concatenation) k1_current = key_states # [batch, num_kv_heads, 1, head_dim] v1_current = value_states # [batch, num_kv_heads, 1, head_dim] # Concatenate with past shared KV cache for attention computation if past_shared_key is not None and past_shared_value is not None: key_states = torch.cat([past_shared_key, key_states], dim=2) value_states = torch.cat([past_shared_value, value_states], dim=2) # Repeat KV for GQA key_states = repeat_kv(key_states, self.num_key_value_groups) value_states = repeat_kv(value_states, self.num_key_value_groups) attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) if attention_mask is not None: causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] attn_weights = attn_weights + causal_mask attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype) attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training) attn_output = torch.matmul(attn_weights, value_states) attn_output = attn_output.transpose(1, 2).contiguous() attn_output = attn_output.reshape(bsz, q_len, -1) attn_output = self.o_proj(attn_output) return attn_output, k1_current, v1_current def forward_decode_loop2( self, hidden_states: torch.Tensor, k1: torch.Tensor, v1: torch.Tensor, past_shared_key: Optional[torch.Tensor], past_shared_value: Optional[torch.Tensor], past_local_key: Optional[torch.Tensor], past_local_value: Optional[torch.Tensor], gate_proj: LoopGateProjection, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, loop_window_size: int = 64, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Forward pass for Loop 2 in decode stage with mixed attention. Args: hidden_states: Current hidden states [batch, 1, hidden_size] k1: Key from Loop 1 (current token) [batch, num_kv_heads, 1, head_dim] v1: Value from Loop 1 (current token) [batch, num_kv_heads, 1, head_dim] past_shared_key: Past shared keys from cache [batch, num_kv_heads, past_len, head_dim] past_shared_value: Past shared values from cache [batch, num_kv_heads, past_len, head_dim] past_local_key: Past local keys from cache [batch, num_kv_heads, window_len, head_dim] past_local_value: Past local values from cache [batch, num_kv_heads, window_len, head_dim] gate_proj: Gate projection module attention_mask: Causal attention mask position_ids: Position IDs loop_window_size: Window size for sliding window attention Returns: output: Attention output [batch, 1, hidden_size] k2: Current key [batch, num_kv_heads, 1, head_dim] v2: Current value [batch, num_kv_heads, 1, head_dim] """ bsz, q_len, _ = hidden_states.size() # Get Q2, K2, V2 for current loop q2, k2, v2 = self.get_qkv(hidden_states, position_ids) # Compute gate: g = sigmoid(linear(Q2)) gate = gate_proj(q2) # [batch, num_heads, 1, 1] # For attention A: concatenate past shared KV with current k1, v1 (full global context) if past_shared_key is not None and past_shared_value is not None: k1_full = torch.cat([past_shared_key, k1], dim=2) v1_full = torch.cat([past_shared_value, v1], dim=2) else: k1_full = k1 v1_full = v1 # For attention B: concatenate past local KV with current k2, v2 (sliding window) if past_local_key is not None and past_local_value is not None: k2_full = torch.cat([past_local_key, k2], dim=2) v2_full = torch.cat([past_local_value, v2], dim=2) else: k2_full = k2 v2_full = v2 # Repeat KV for GQA k1_expanded = repeat_kv(k1_full, self.num_key_value_groups) v1_expanded = repeat_kv(v1_full, self.num_key_value_groups) k2_expanded = repeat_kv(k2_full, self.num_key_value_groups) v2_expanded = repeat_kv(v2_full, self.num_key_value_groups) # Attention A: Q2 @ K1_full, V1_full (global, full sequence) head_dim = q2.shape[-1] attn_weights_A = torch.matmul(q2, k1_expanded.transpose(2, 3)) / math.sqrt(head_dim) if attention_mask is not None: causal_mask = attention_mask[:, :, :, : k1_expanded.shape[-2]] attn_weights_A = attn_weights_A + causal_mask attn_weights_A = nn.functional.softmax(attn_weights_A, dim=-1, dtype=torch.float32).to(q2.dtype) attn_A = torch.matmul(attn_weights_A, v1_expanded) # Attention B: Q2 @ K2_full, V2_full (local sliding window) attn_weights_B = torch.matmul(q2, k2_expanded.transpose(2, 3)) / math.sqrt(head_dim) if attention_mask is not None: causal_mask = attention_mask[:, :, :, : k2_expanded.shape[-2]] attn_weights_B = attn_weights_B + causal_mask # Apply sliding window mask q_len_attn = q2.shape[2] k_len_attn = k2_expanded.shape[2] if q_len_attn <= loop_window_size: # If sequence fits in window, use standard attention attn_weights_B = nn.functional.softmax(attn_weights_B, dim=-1, dtype=torch.float32).to(q2.dtype) else: # Apply sliding window mask row_idx = torch.arange(q_len_attn, device=q2.device).unsqueeze(1) col_idx = torch.arange(k_len_attn, device=q2.device).unsqueeze(0) window_mask = (col_idx > row_idx) | (col_idx < row_idx - loop_window_size + 1) window_mask = window_mask.unsqueeze(0).unsqueeze(0) attn_weights_B = attn_weights_B.masked_fill(window_mask, float('-inf')) attn_weights_B = nn.functional.softmax(attn_weights_B, dim=-1, dtype=torch.float32).to(q2.dtype) attn_B = torch.matmul(attn_weights_B, v2_expanded) # Mixed attention: gate * A + (1 - gate) * B mixed_attn = gate * attn_A + (1 - gate) * attn_B # Reshape and apply output projection bsz, num_heads, seq_len, head_dim = mixed_attn.shape mixed_attn = mixed_attn.transpose(1, 2).contiguous().reshape(bsz, seq_len, -1) attn_output = self.o_proj(mixed_attn) return attn_output, k2, v2
class IQuestLoopCoderDecoderLayer(nn.Module): """Transformer decoder layer.""" def __init__(self, config: IQuestLoopCoderConfig, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.self_attn = IQuestLoopCoderAttention(config=config, layer_idx=layer_idx) self.mlp = IQuestLoopCoderMLP(config) self.input_layernorm = IQuestLoopCoderRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_attention_layernorm = IQuestLoopCoderRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
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, **kwargs, ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: residual = hidden_states hidden_states = self.input_layernorm(hidden_states) hidden_states, self_attn_weights, present_key_value = 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, **kwargs, ) hidden_states = residual + hidden_states
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,) if use_cache: outputs += (present_key_value,) return outputs def forward_loop2_mixed( self, hidden_states: torch.Tensor, k1: torch.Tensor, v1: torch.Tensor, gate_proj: LoopGateProjection, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, loop_window_size: int = 64, ) -> Tuple[torch.Tensor, float]: """Forward pass for Loop 2+ with mixed attention. Args: hidden_states: Current hidden states k1: Key from Loop 1 [batch, num_kv_heads, seq_len, head_dim] v1: Value from Loop 1 [batch, num_kv_heads, seq_len, head_dim] gate_proj: Gate projection module for this layer attention_mask: Causal attention mask position_ids: Position IDs loop_window_size: Window size for sliding window attention Returns: output hidden states, gate mean value """ residual = hidden_states hidden_states_normed = self.input_layernorm(hidden_states) # Get Q2, K2, V2 for current loop q2, k2, v2 = self.self_attn.get_qkv(hidden_states_normed, position_ids) # Compute gate: g = sigmoid(linear(Q2)) # q2: [batch, num_heads, seq_len, head_dim] gate = gate_proj(q2) # [batch, num_heads, seq_len, 1] gate_mean = gate.detach().mean().item() # Repeat K1, V1 for GQA k1_expanded = repeat_kv(k1, self.self_attn.num_key_value_groups) v1_expanded = repeat_kv(v1, self.self_attn.num_key_value_groups) k2_expanded = repeat_kv(k2, self.self_attn.num_key_value_groups) v2_expanded = repeat_kv(v2, self.self_attn.num_key_value_groups) # Attention A: Q2 @ K1, V1 (global, full sequence) attn_A = self._compute_attention(q2, k1_expanded, v1_expanded, attention_mask) # Attention B: Q2 @ K2, V2 (local sliding window) attn_B = self._compute_attention_with_window(q2, k2_expanded, v2_expanded, attention_mask, loop_window_size) # Mixed attention: gate * A + (1 - gate) * B # attn_A, attn_B: [batch, num_heads, seq_len, head_dim] mixed_attn = gate * attn_A + (1 - gate) * attn_B # Reshape and apply output projection bsz, num_heads, seq_len, head_dim = mixed_attn.shape mixed_attn = mixed_attn.transpose(1, 2).contiguous().reshape(bsz, seq_len, -1) hidden_states = self.self_attn.o_proj(mixed_attn) hidden_states = residual + hidden_states # MLP residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = residual + hidden_states return hidden_states, gate_mean def _compute_attention( self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: Optional[torch.Tensor], ) -> torch.Tensor: """Standard attention computation.""" head_dim = query.shape[-1] attn_weights = torch.matmul(query, key.transpose(2, 3)) / math.sqrt(head_dim) if attention_mask is not None: causal_mask = attention_mask[:, :, :, : key.shape[-2]] attn_weights = attn_weights + causal_mask attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) attn_output = torch.matmul(attn_weights, value) return attn_output def _compute_attention_with_window( self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: Optional[torch.Tensor], window_size: int, ) -> torch.Tensor: """Attention with sliding window.""" q_len = query.shape[2] k_len = key.shape[2] head_dim = query.shape[-1] # If sequence fits in window, use standard attention if q_len <= window_size: return self._compute_attention(query, key, value, attention_mask) attn_weights = torch.matmul(query, key.transpose(2, 3)) / math.sqrt(head_dim) # Apply causal mask if attention_mask is not None: causal_mask = attention_mask[:, :, :, : key.shape[-2]] attn_weights = attn_weights + causal_mask # Apply sliding window mask row_idx = torch.arange(q_len, device=query.device).unsqueeze(1) col_idx = torch.arange(k_len, device=query.device).unsqueeze(0) # Can only attend to positions in [i - window_size + 1, i] window_mask = (col_idx > row_idx) | (col_idx < row_idx - window_size + 1) window_mask = window_mask.unsqueeze(0).unsqueeze(0) attn_weights = attn_weights.masked_fill(window_mask, float('-inf')) attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) attn_output = torch.matmul(attn_weights, value) return attn_output
class IQuestLoopCoderPreTrainedModel(PreTrainedModel): """Base class for IQuestLoopCoder models.""" config_class = IQuestLoopCoderConfig base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["IQuestLoopCoderDecoderLayer"] _skip_keys_device_placement = ["past_key_values"] _supports_cache_class = True _supports_static_cache = True
def _init_weights(self, 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_()
class IQuestLoopCoderModel(IQuestLoopCoderPreTrainedModel): """IQuestLoopCoder Transformer decoder model.""" def __init__(self, config: IQuestLoopCoderConfig): 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([ IQuestLoopCoderDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers) ]) self.norm = IQuestLoopCoderRMSNorm(config.hidden_size, eps=config.rms_norm_eps) # Gate projections for Loop 2+ (one per layer) self.gate_projections = nn.ModuleList([ LoopGateProjection(config.num_attention_heads, config.head_dim) for _ in range(config.num_hidden_layers) ]) # Loop configuration self.loop_num = config.loop_num self.loop_window_size = config.loop_window_size self.gradient_checkpointing = False self.post_init()
def get_input_embeddings(self): return self.embed_tokens
def set_input_embeddings(self, value): self.embed_tokens = value
def forward( self, input_ids: 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, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, ) -> Union[Tuple, 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 return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids)
seq_length = inputs_embeds.shape[1] # Determine which forward path to use: # 1. If past_key_values exists and seq_length == 1: autoregressive generation step # -> Use standard attention with KV cache (no loop needed for single token) # 2. Otherwise (prefill or training): use loop mechanism is_generation_step = past_key_values is not None and seq_length == 1 if is_generation_step: # Autoregressive generation: single token, use KV cache return self._forward_with_cache( inputs_embeds=inputs_embeds, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, cache_position=cache_position, ) # Prefill or training: use loop mechanism return self._forward_loop( inputs_embeds=inputs_embeds, attention_mask=attention_mask, position_ids=position_ids, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, use_cache=use_cache, cache_position=cache_position, ) def _forward_loop( self, inputs_embeds: torch.Tensor, attention_mask: Optional[torch.Tensor], position_ids: Optional[torch.LongTensor], output_attentions: bool, output_hidden_states: bool, return_dict: bool, use_cache: bool = False, cache_position: Optional[torch.LongTensor] = None, ) -> Union[Tuple, BaseModelOutputWithPast]: """Forward with loop mechanism (for training and prefill). This implements the Loop mechanism: - Loop 1: Standard attention, stores K1, V1 for each layer - Loop 2+: Mixed attention with gated combination of global (K1,V1) and local (K2,V2) """ batch_size, seq_length, _ = inputs_embeds.shape if position_ids is None: device = inputs_embeds.device position_ids = torch.arange(seq_length, dtype=torch.long, device=device).unsqueeze(0) if cache_position is None: cache_position = torch.arange(seq_length, device=inputs_embeds.device) # Create causal mask causal_mask = self._update_causal_mask(attention_mask, inputs_embeds, cache_position, None, output_attentions) hidden_states = inputs_embeds all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None # For KV cache during prefill - use IQuestLoopCoderCache # In prefill, past_key_values should be None, so we create a new cache if use_cache: next_decoder_cache = IQuestLoopCoderCache(self.loop_window_size, len(self.layers)) else: next_decoder_cache = None # ============ Loop 1: Standard forward, store K1, V1 in shared cache ============ for layer_idx, decoder_layer in enumerate(self.layers): if output_hidden_states: all_hidden_states += (hidden_states,) # Get K1, V1 before standard forward (from original hidden_states, after layernorm) hidden_states_normed = decoder_layer.input_layernorm(hidden_states) q1, k1, v1 = decoder_layer.self_attn.get_qkv(hidden_states_normed, position_ids) # Store K1, V1 in shared cache if use_cache: next_decoder_cache.update_shared(k1, v1, layer_idx) # Standard forward layer_outputs = decoder_layer( hidden_states, attention_mask=causal_mask, position_ids=position_ids, past_key_value=None, output_attentions=output_attentions, use_cache=False, ) hidden_states = layer_outputs[0] if output_attentions: all_self_attns += (layer_outputs[1],) # ============ Loop 2 to loop_num: Mixed attention, store in local cache ============ for loop_idx in range(2, self.loop_num + 1): for layer_idx, decoder_layer in enumerate(self.layers): # Get K1, V1 from shared cache k1, v1 = next_decoder_cache.get_shared(layer_idx) if use_cache else (None, None) if k1 is None or v1 is None: # Fallback: compute K1, V1 if not in cache (shouldn't happen in prefill) hidden_states_normed = decoder_layer.input_layernorm(hidden_states) _, k1, v1 = decoder_layer.self_attn.get_qkv(hidden_states_normed, position_ids) gate_proj = self.gate_projections[layer_idx] hidden_states, gate_mean = decoder_layer.forward_loop2_mixed( hidden_states, k1=k1, v1=v1, gate_proj=gate_proj, attention_mask=causal_mask, position_ids=position_ids, loop_window_size=self.loop_window_size, ) # Store Loop 2+ KV in local cache (only for loop_idx == 2) if use_cache and loop_idx == 2: hidden_states_normed = decoder_layer.input_layernorm(hidden_states) _, k2, v2 = decoder_layer.self_attn.get_qkv(hidden_states_normed, position_ids) next_decoder_cache.update_local(k2, v2, layer_idx) hidden_states = self.norm(hidden_states) if output_hidden_states: all_hidden_states += (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, next_decoder_cache, all_hidden_states, all_self_attns] if v is not None) return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=next_decoder_cache, hidden_states=all_hidden_states, attentions=all_self_attns, ) def _forward_with_cache( self, inputs_embeds: torch.Tensor, attention_mask: Optional[torch.Tensor], position_ids: Optional[torch.LongTensor], past_key_values: Optional[Cache], use_cache: bool, output_attentions: bool, output_hidden_states: bool, return_dict: bool, cache_position: Optional[torch.LongTensor], ) -> Union[Tuple, BaseModelOutputWithPast]: """Forward with KV cache using loop mechanism (for inference generation). Loop 1: Standard attention, uses shared KV cache (previous tokens + current token) Loop 2+: Mixed attention, uses local KV cache (sliding window) """ batch_size, seq_length, _ = inputs_embeds.shape 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 + seq_length, 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) # Ensure we're using IQuestLoopCoderCache if use_cache: if not isinstance(past_key_values, IQuestLoopCoderCache): # Convert to IQuestLoopCoderCache if needed next_decoder_cache = IQuestLoopCoderCache(self.loop_window_size, len(self.layers)) # Copy existing cache if possible if past_key_values is not None: for layer_idx in range(len(self.layers)): try: past_k = past_key_values.key_cache[layer_idx] if hasattr(past_key_values, 'key_cache') else None past_v = past_key_values.value_cache[layer_idx] if hasattr(past_key_values, 'value_cache') else None if past_k is not None and past_v is not None: next_decoder_cache.update_shared(past_k, past_v, layer_idx) except: pass else: next_decoder_cache = past_key_values else: next_decoder_cache = None hidden_states = inputs_embeds all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None # ============ Loop 1: Standard attention, store in shared cache ============ for layer_idx, decoder_layer in enumerate(self.layers): if output_hidden_states: all_hidden_states += (hidden_states,) # Get past shared KV cache past_shared_key, past_shared_value = None, None if next_decoder_cache is not None: past_shared_key, past_shared_value = next_decoder_cache.get_shared(layer_idx) # Forward Loop 1 attn_output, k1, v1 = decoder_layer.self_attn.forward_decode_loop1( hidden_states=decoder_layer.input_layernorm(hidden_states), past_shared_key=past_shared_key, past_shared_value=past_shared_value, attention_mask=causal_mask, position_ids=position_ids, cache_position=cache_position, ) # Update shared cache with current token's Loop 1 KV if use_cache: next_decoder_cache.update_shared(k1, v1, layer_idx) hidden_states = hidden_states + attn_output # MLP residual = hidden_states hidden_states = decoder_layer.post_attention_layernorm(hidden_states) hidden_states = decoder_layer.mlp(hidden_states) hidden_states = residual + hidden_states if output_attentions: all_self_attns += (None,) # We don't return attention weights in decode loop # ============ Loop 2 to loop_num: Mixed attention, store in local cache ============ # Store k1, v1 from Loop 1 for use in Loop 2+ loop1_kv = [] for layer_idx in range(len(self.layers)): if next_decoder_cache is not None: k1_full, v1_full = next_decoder_cache.get_shared(layer_idx) if k1_full is not None and v1_full is not None: # Get only the last token (current token) loop1_kv.append((k1_full[:, :, -1:, :], v1_full[:, :, -1:, :], k1_full, v1_full)) else: loop1_kv.append((None, None, None, None)) else: loop1_kv.append((None, None, None, None)) for loop_idx in range(2, self.loop_num + 1): for layer_idx, decoder_layer in enumerate(self.layers): # Get k1, v1 (current token's Loop 1 KV) and full shared cache k1_current, v1_current, k1_full, v1_full = loop1_kv[layer_idx] if k1_current is None or v1_current is None: continue # Get past local KV cache past_local_key, past_local_value = None, None if next_decoder_cache is not None: past_local_key, past_local_value = next_decoder_cache.get_local(layer_idx) gate_proj = self.gate_projections[layer_idx] # Forward Loop 2+ attn_output, k2, v2 = decoder_layer.self_attn.forward_decode_loop2( hidden_states=decoder_layer.input_layernorm(hidden_states), k1=k1_current, v1=v1_current, past_shared_key=k1_full[:, :, :-1, :] if k1_full is not None and k1_full.shape[2] > 1 else None, past_shared_value=v1_full[:, :, :-1, :] if v1_full is not None and v1_full.shape[2] > 1 else None, past_local_key=past_local_key, past_local_value=past_local_value, gate_proj=gate_proj, attention_mask=causal_mask, position_ids=position_ids, loop_window_size=self.loop_window_size, ) # Update local cache with current token's Loop 2+ KV if use_cache and loop_idx == 2: next_decoder_cache.update_local(k2, v2, layer_idx) hidden_states = hidden_states + attn_output # MLP residual = hidden_states hidden_states = decoder_layer.post_attention_layernorm(hidden_states) hidden_states = decoder_layer.mlp(hidden_states) hidden_states = residual + hidden_states hidden_states = self.norm(hidden_states) if output_hidden_states: all_hidden_states += (hidden_states,) next_cache = next_decoder_cache if use_cache else None if not return_dict: return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None) return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=next_cache, hidden_states=all_hidden_states, attentions=all_self_attns, ) def _update_causal_mask( self, attention_mask: torch.Tensor, input_tensor: torch.Tensor, cache_position: torch.Tensor, past_key_values: Cache, output_attentions: bool, ): """Create causal attention mask.""" dtype, device = input_tensor.dtype, input_tensor.device min_dtype = torch.finfo(dtype).min sequence_length = input_tensor.shape[1] # Determine target length for attention if past_key_values is not None: # For DynamicCache: use get_seq_length() to get cached length # target_length = cached_length + current_sequence_length past_length = past_key_values.get_seq_length() target_length = past_length + sequence_length elif attention_mask is not None: target_length = attention_mask.shape[-1] else: target_length = sequence_length # Create causal mask causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device) if sequence_length != 1: # For prefill: standard causal mask causal_mask = torch.triu(causal_mask, diagonal=1) # Adjust for cache position (for generation steps after prefill) causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1) causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1) if attention_mask is not None: causal_mask = causal_mask.clone() mask_length = attention_mask.shape[-1] if mask_length <= target_length: padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :] padding_mask = padding_mask == 0 causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(padding_mask, min_dtype) return causal_mask
class IQuestLoopCoderForCausalLM(IQuestLoopCoderPreTrainedModel, GenerationMixin): """IQuestLoopCoder model with a causal language modeling head.""" _tied_weights_keys = ["lm_head.weight"]
def __init__(self, config): super().__init__(config) self.model = IQuestLoopCoderModel(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.post_init()
def get_input_embeddings(self): return self.model.embed_tokens
def set_input_embeddings(self, value): self.model.embed_tokens = value
def get_output_embeddings(self): return self.lm_head
def set_output_embeddings(self, new_embeddings): self.lm_head = new_embeddings
def set_decoder(self, decoder): self.model = decoder
def get_decoder(self): return self.model
def forward( self, input_ids: 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, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, ) -> Union[Tuple, CausalLMOutputWithPast]: 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 return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, cache_position=cache_position, )
hidden_states = outputs[0] logits = self.lm_head(hidden_states) logits = logits.float()
loss = None if labels is not None: shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() loss_fct = nn.CrossEntropyLoss() shift_logits = shift_logits.view(-1, self.config.vocab_size) shift_labels = shift_labels.view(-1) shift_labels = shift_labels.to(shift_logits.device) loss = loss_fct(shift_logits, shift_labels)
if not return_dict: output = (logits,) + outputs[1:] return (loss,) + output if loss is not None else output
return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
def prepare_inputs_for_generation( self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, cache_position=None, use_cache=True, **kwargs, ): past_length = 0 if past_key_values is not None: past_length = past_key_values.get_seq_length() if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]: input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :] elif past_length < input_ids.shape[1]: input_ids = input_ids[:, past_length:]
if cache_position is None: cache_position = torch.arange(past_length, past_length + input_ids.shape[1], device=input_ids.device) elif use_cache: cache_position = cache_position[-input_ids.shape[1]:]
position_ids = cache_position.unsqueeze(0)
if inputs_embeds is not None and past_key_values is None: model_inputs = {"inputs_embeds": inputs_embeds} else: model_inputs = {"input_ids": input_ids.contiguous()}
model_inputs.update( { "position_ids": position_ids, "cache_position": cache_position, "past_key_values": past_key_values, "use_cache": use_cache, "attention_mask": attention_mask, } ) return model_inputs
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748{ "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>" ], "bos_token": { "content": "<s>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false }, "eos_token": { "content": "<|im_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "pad_token": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false }, "unk_token": { "content": "<unk>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": true }}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 1345108123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285{ "add_bos_token": false, "add_eos_token": false, "add_prefix_space": 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 }, "75880": { "content": "<|CLS|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "75881": { "content": "<|SEP|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "75882": { "content": "<|EOD|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "75883": { "content": "<|MASK|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "75884": { "content": "<|PAD|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true } }, "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>", "clean_up_tokenization_spaces": false, "eos_token": "<|im_end|>", "extra_special_tokens": {}, "legacy": true, "model_max_length": 131072, "pad_token": "<|endoftext|>", "padding_side": "right", "sp_model_kwargs": {}, "split_special_tokens": false, "tokenizer_class": "IQuestCoderTokenizer", "unk_token": "<unk>", "use_default_system_prompt": false, "use_fast": false}README.mdAdded+40
__init__.pyAdded+26
added_tokens.jsonAdded+29
chat_template.jinjaAdded+69
config.jsonAdded+47
configuration_iquestloopcoder.pyAdded+132
generation_config.jsonAdded+6
model-00001-of-00007.safetensorsAdded+3
model-00002-of-00007.safetensorsAdded+3
model-00003-of-00007.safetensorsAdded+3
model-00004-of-00007.safetensorsAdded+3
model-00005-of-00007.safetensorsAdded+3
model-00006-of-00007.safetensorsAdded+3
model-00007-of-00007.safetensorsAdded+3
model.safetensors.index.jsonAdded
modeling_iquestloopcoder.pyAdded+1421
special_tokens_map.jsonAdded+48
tokenization_iquestcoder.pyAdded+552
tokenizer.modelAdded+3
tokenizer_config.jsonAdded+285