Transformers
English
time-series
time-series-language-model
latent-reasoning
reasoning
ecg
sleep-staging
human-activity-recognition
llama-3.2
qwen3
Run this model with HF Jobs
Run leochen085/Lapras 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/leochen085/Lapras. 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/leochen085/Lapras 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.
Instructions to use leochen085/Lapras with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use leochen085/Lapras with Transformers:
# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("leochen085/Lapras", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- chatts/lapras_ecg/added_tokens.jsonAdded+32
- chatts/lapras_ecg/chat_template.jinjaAdded+89
- chatts/lapras_ecg/config.jsonAdded+90
- chatts/lapras_ecg/configuration_qwen3_ts.pyAdded+225
- chatts/lapras_ecg/generation_config.jsonAdded+13
- chatts/lapras_ecg/lapras_run_config.jsonAdded+12
- chatts/lapras_ecg/merges.txtAdded
- chatts/lapras_ecg/modeling_qwen3_ts.pyAdded+601
- chatts/lapras_ecg/processing_qwen3_ts.pyAdded+224
- chatts/lapras_ecg/processor_config.jsonAdded+6
- chatts/lapras_ecg/pytorch_model.bin.index.jsonAdded+424
- chatts/lapras_ecg/special_tokens_map.jsonAdded+20
- chatts/lapras_ecg/tokenizer_config.jsonAdded+265
- chatts/lapras_ecg/vocab.jsonAdded
- chatts/lapras_engine/added_tokens.jsonAdded+32
- chatts/lapras_engine/chat_template.jinjaAdded+89
- chatts/lapras_engine/config.jsonAdded+90
- chatts/lapras_engine/configuration_qwen3_ts.pyAdded+225
- chatts/lapras_engine/generation_config.jsonAdded+13
- chatts/lapras_engine/lapras_run_config.jsonAdded+12
- chatts/lapras_engine/merges.txtAdded
- chatts/lapras_engine/modeling_qwen3_ts.pyAdded+601
- chatts/lapras_engine/processing_qwen3_ts.pyAdded+224
- chatts/lapras_engine/processor_config.jsonAdded+6
- chatts/lapras_engine/pytorch_model.bin.index.jsonAdded+425
- chatts/lapras_engine/tokenizer_config.jsonAdded+265
- chatts/lapras_engine/vocab.jsonAdded
- chatts/lapras_har/added_tokens.jsonAdded+32
- chatts/lapras_har/chat_template.jinjaAdded+89
- chatts/lapras_har/config.jsonAdded+90
- chatts/lapras_har/configuration_qwen3_ts.pyAdded+225
- chatts/lapras_har/generation_config.jsonAdded+13
- chatts/lapras_har/lapras_run_config.jsonAdded+12
- chatts/lapras_har/merges.txtAdded
- chatts/lapras_har/modeling_qwen3_ts.pyAdded+601
- chatts/lapras_har/processing_qwen3_ts.pyAdded+224
- chatts/lapras_har/processor_config.jsonAdded+6
- chatts/lapras_har/pytorch_model.bin.index.jsonAdded+425
- chatts/lapras_har/special_tokens_map.jsonAdded+20
- chatts/lapras_har/tokenizer_config.jsonAdded+265
- chatts/lapras_har/vocab.jsonAdded
- chatts/lapras_sleep/added_tokens.jsonAdded+32
- chatts/lapras_sleep/chat_template.jinjaAdded+89
- chatts/lapras_sleep/config.jsonAdded+90
- chatts/lapras_sleep/configuration_qwen3_ts.pyAdded+225
- chatts/lapras_sleep/generation_config.jsonAdded+13
- chatts/lapras_sleep/lapras_run_config.jsonAdded+12
- chatts/lapras_sleep/merges.txtAdded
- chatts/lapras_sleep/modeling_qwen3_ts.pyAdded+601
- chatts/lapras_sleep/processing_qwen3_ts.pyAdded+224
1234567891011121314151617181920212223242526272829303132{ "</think>": 151668, "</tool_call>": 151658, "</tool_response>": 151666, "<think>": 151667, "<tool_call>": 151657, "<tool_response>": 151665, "<ts/>": 151670, "<ts>": 151669, "<|bot|>": 151671, "<|box_end|>": 151649, "<|box_start|>": 151648, "<|endoftext|>": 151643, "<|eot|>": 151672, "<|file_sep|>": 151664, "<|fim_middle|>": 151660, "<|fim_pad|>": 151662, "<|fim_prefix|>": 151659, "<|fim_suffix|>": 151661, "<|im_end|>": 151645, "<|im_start|>": 151644, "<|image_pad|>": 151655, "<|object_ref_end|>": 151647, "<|object_ref_start|>": 151646, "<|quad_end|>": 151651, "<|quad_start|>": 151650, "<|repo_name|>": 151663, "<|video_pad|>": 151656, "<|vision_end|>": 151653, "<|vision_pad|>": 151654, "<|vision_start|>": 151652}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889{%- if tools %} {{- '<|im_start|>system\n' }} {%- if messages[0].role == 'system' %} {{- messages[0].content + '\n\n' }} {%- 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' }} {%- 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 message.content is string 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.content is string %} {%- set content = message.content %} {%- else %} {%- set content = '' %} {%- endif %} {%- if (message.role == "user") or (message.role == "system" and not loop.first) %} {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} {%- elif message.role == "assistant" %} {%- set reasoning_content = '' %} {%- if message.reasoning_content is string %} {%- set reasoning_content = message.reasoning_content %} {%- else %} {%- if '</think>' in content %} {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %} {%- set content = content.split('</think>')[-1].lstrip('\n') %} {%- endif %} {%- endif %} {%- if loop.index0 > ns.last_query_index %} {%- if loop.last or (not loop.last and reasoning_content) %} {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }} {%- else %} {{- '<|im_start|>' + message.role + '\n' + content }} {%- endif %} {%- else %} {{- '<|im_start|>' + message.role + '\n' + content }} {%- endif %} {%- 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' }} {{- 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' }} {%- if enable_thinking is defined and enable_thinking is false %} {{- '<think>\n\n</think>\n\n' }} {%- endif %}{%- endif %}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990{ "architectures": [ "Qwen3TSForCausalLM" ], "attention_bias": false, "attention_dropout": 0.0, "auto_map": { "AutoConfig": "configuration_qwen3_ts.Qwen3TSConfig", "AutoModel": "modeling_qwen3_ts.Qwen3TSForCausalLM", "AutoModelForCausalLM": "modeling_qwen3_ts.Qwen3TSForCausalLM", "AutoProcessor": "processing_qwen3_ts.Qwen3TSProcessor" }, "bos_token_id": 151643, "eos_token_id": 151645, "head_dim": 128, "hidden_act": "silu", "hidden_size": 4096, "ignore_index": -100, "initializer_range": 0.02, "intermediate_size": 12288, "layer_types": [ "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention" ], "max_position_embeddings": 40960, "max_window_layers": 36, "model_type": "qwen3ts", "num_attention_heads": 32, "num_hidden_layers": 36, "num_key_value_heads": 8, "pad_token_id": 151643, "rms_norm_eps": 1e-06, "rope_scaling": null, "rope_theta": 1000000, "sliding_window": null, "tie_word_embeddings": false, "torch_dtype": "bfloat16", "transformers_version": "4.55.4", "ts": { "embedding_dim": 16, "hidden_size": 4096, "max_length": 32768, "max_sequence_length": 8192, "num_features": 2, "num_layers": 5, "patch_size": 32, "use_layer_norm": false, "use_position_embedding": true, "use_position_idx": false }, "ts_token_end_index": 151670, "ts_token_start_index": 151669, "use_cache": false, "use_sliding_window": false, "vocab_size": 151936}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225# coding=utf-8# Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Qwen3 model configuration"""
from transformers.configuration_utils import PretrainedConfigfrom transformers.modeling_rope_utils import rope_config_validationfrom transformers.utils import logging
logger = logging.get_logger(__name__)
class Qwen3TSConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`Qwen3Model`]. It is used to instantiate a Qwen3 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of Qwen3-8B [Qwen/Qwen3-8B](https://huggingface.co/Qwen/Qwen3-8B).
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.
Args: vocab_size (`int`, *optional*, defaults to 151936): Vocabulary size of the Qwen3 model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`Qwen3Model`] hidden_size (`int`, *optional*, defaults to 4096): Dimension of the hidden representations. intermediate_size (`int`, *optional*, defaults to 22016): Dimension of the MLP representations. num_hidden_layers (`int`, *optional*, defaults to 32): Number of hidden layers in the Transformer encoder. num_attention_heads (`int`, *optional*, defaults to 32): Number of attention heads for each attention layer in the Transformer encoder. num_key_value_heads (`int`, *optional*, defaults to 32): This is the number of key_value heads that should be used to implement Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details, check out [this paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`. head_dim (`int`, *optional*, defaults to 128): The attention head dimension. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`): The non-linear activation function (function or string) in the decoder. max_position_embeddings (`int`, *optional*, defaults to 32768): The maximum sequence length that this model might ever be used with. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. rms_norm_eps (`float`, *optional*, defaults to 1e-06): The epsilon used by the rms normalization layers. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True`. tie_word_embeddings (`bool`, *optional*, defaults to `False`): Whether the model's input and output word embeddings should be tied. rope_theta (`float`, *optional*, defaults to 10000.0): The base period of the RoPE embeddings. rope_scaling (`Dict`, *optional*): Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value accordingly. Expected contents: `rope_type` (`str`): The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope', 'llama3'], with 'default' being the original RoPE implementation. `factor` (`float`, *optional*): Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In most scaling types, a `factor` of x will enable the model to handle sequences of length x * original maximum pre-trained length. `original_max_position_embeddings` (`int`, *optional*): Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during pretraining. `attention_factor` (`float`, *optional*): Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention computation. If unspecified, it defaults to value recommended by the implementation, using the `factor` field to infer the suggested value. `beta_fast` (`float`, *optional*): Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear ramp function. If unspecified, it defaults to 32. `beta_slow` (`float`, *optional*): Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear ramp function. If unspecified, it defaults to 1. `short_factor` (`list[float]`, *optional*): Only used with 'longrope'. The scaling factor to be applied to short contexts (< `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 `long_factor` (`list[float]`, *optional*): Only used with 'longrope'. The scaling factor to be applied to long contexts (< `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 `low_freq_factor` (`float`, *optional*): Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE `high_freq_factor` (`float`, *optional*): Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`): Whether to use a bias in the query, key, value and output projection layers during self-attention. use_sliding_window (`bool`, *optional*, defaults to `False`): Whether to use sliding window attention. sliding_window (`int`, *optional*, defaults to 4096): Sliding window attention (SWA) window size. If not specified, will default to `4096`. max_window_layers (`int`, *optional*, defaults to 28): The number of layers using full attention. The first `max_window_layers` layers will use full attention, while any additional layer afterwards will use SWA (Sliding Window Attention). layer_types (`list`, *optional*): Attention pattern for each layer. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities.
```python >>> from transformers import Qwen3Model, Qwen3Config
>>> # Initializing a Qwen3 style configuration >>> configuration = Qwen3Config()
>>> # Initializing a model from the Qwen3-8B style configuration >>> model = Qwen3Model(configuration)
>>> # Accessing the model configuration >>> configuration = model.config ```"""
model_type = "qwen3ts" keys_to_ignore_at_inference = ["past_key_values"]
# Default tensor parallel plan for base model `Qwen3` base_model_tp_plan = { "layers.*.self_attn.q_proj": "colwise", "layers.*.self_attn.k_proj": "colwise", "layers.*.self_attn.v_proj": "colwise", "layers.*.self_attn.o_proj": "rowwise", "layers.*.mlp.gate_proj": "colwise", "layers.*.mlp.up_proj": "colwise", "layers.*.mlp.down_proj": "rowwise", } base_model_pp_plan = { "embed_tokens": (["input_ids"], ["inputs_embeds"]), "layers": (["hidden_states", "attention_mask"], ["hidden_states"]), "norm": (["hidden_states"], ["hidden_states"]), }
def __init__( self, vocab_size=151936, hidden_size=4096, intermediate_size=22016, num_hidden_layers=32, num_attention_heads=32, num_key_value_heads=32, head_dim=128, hidden_act="silu", max_position_embeddings=32768, initializer_range=0.02, rms_norm_eps=1e-6, use_cache=True, tie_word_embeddings=False, rope_theta=10000.0, rope_scaling=None, attention_bias=False, use_sliding_window=False, sliding_window=4096, max_window_layers=28, layer_types=None, attention_dropout=0.0, **kwargs, ): self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.use_sliding_window = use_sliding_window self.sliding_window = sliding_window if self.use_sliding_window else None self.max_window_layers = max_window_layers
# for backward compatibility if num_key_value_heads is None: num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads self.head_dim = head_dim self.hidden_act = hidden_act self.initializer_range = initializer_range self.rms_norm_eps = rms_norm_eps self.use_cache = use_cache self.rope_theta = rope_theta self.rope_scaling = rope_scaling self.attention_bias = attention_bias self.attention_dropout = attention_dropout # Validate the correctness of rotary position embeddings parameters # BC: if there is a 'type' field, move it to 'rope_type'. if self.rope_scaling is not None and "type" in self.rope_scaling: self.rope_scaling["rope_type"] = self.rope_scaling["type"] rope_config_validation(self)
self.layer_types = layer_types if self.layer_types is None: self.layer_types = [ "sliding_attention" if self.sliding_window is not None and i >= self.max_window_layers else "full_attention" for i in range(self.num_hidden_layers) ]
super().__init__( tie_word_embeddings=tie_word_embeddings, **kwargs, )
__all__ = ["Qwen3TSConfig"]12345678910111213{ "bos_token_id": 151643, "do_sample": true, "eos_token_id": [ 151645, 151643 ], "pad_token_id": 151643, "temperature": 0.6, "top_k": 20, "top_p": 0.95, "transformers_version": "4.55.4"}123456789101112{ "stage": "lapras", "template": "chatts", "ts_patch_size": 32, "answer_anchor": "Answer:", "use_cot": null, "num_latent": 6, "projection": { "projection_dim": 2048 }, "remove_eos": true}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601# Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
from typing import Callable, Optional, Union
import torchfrom torch import nnfrom dataclasses import dataclass
from transformers.cache_utils import Cachefrom transformers.generation import GenerationMixinfrom transformers.modeling_flash_attention_utils import FlashAttentionKwargsfrom transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast)from transformers.models.qwen3.modeling_qwen3 import Qwen3PreTrainedModel, Qwen3Modelfrom transformers.modeling_utils import PreTrainedModelfrom transformers.processing_utils import Unpackfrom transformers.utils import auto_docstring, can_return_tuple, logging, ModelOutputfrom .configuration_qwen3_ts import Qwen3TSConfigfrom typing import Any, Dict
logger = logging.get_logger(__name__)
########################MLP TS Embedding#####################class TimeSeriesEmbedding(nn.Module): def __init__(self, config): super(TimeSeriesEmbedding, self).__init__() self.patch_size = config['patch_size'] self.num_layers = config['num_layers'] self.hidden_size = config['hidden_size'] self.num_features = config['num_features'] self.max_sequence_length = config['max_sequence_length'] # Maximum time series length self.use_position_embedding = config.get('use_position_embedding', False) self.use_position_idx = config.get('use_position_idx', False) self.use_layer_norm = config.get('use_layer_norm', False) self.embedding_dim = config.get('embedding_dim', 16) # Embedding dimension if self.use_position_embedding: # Extended vocabulary: [0, max_sequence_length) for real positions, max_sequence_length for padding self.position_embedding = nn.Embedding(self.max_sequence_length + 1, self.embedding_dim) self.padding_idx = self.max_sequence_length # Special index for padding input_size = 1 * self.patch_size + self.embedding_dim * self.patch_size elif self.use_position_idx: input_size = 2 * self.patch_size else: input_size = 1 * self.patch_size # Build MLP layers layers = [] for _ in range(self.num_layers - 1): layers.append(nn.Linear(input_size, self.hidden_size)) layers.append(nn.GELU()) input_size = self.hidden_size
layers.append(nn.Linear(input_size, self.hidden_size)) if self.use_layer_norm: layers.append(nn.LayerNorm(self.hidden_size))
self.mlp = nn.Sequential(*layers)
def forward(self, x: torch.Tensor): batch_size = x.size(0) x = x.reshape(batch_size, -1, self.num_features)
# Extract mask and calculate valid lengths mask = x[:, :, -1].long() valid_lengths = mask.sum(dim=1).long() patch_cnt = (valid_lengths + self.patch_size - 1) // self.patch_size
patches_list = [] # Collect position indices for batch embedding lookup all_position_indices = [] patch_info_list = [] # Store metadata for each patch group for i in range(batch_size): vl = valid_lengths[i].item() pc = patch_cnt[i].item() if pc == 0: continue # Extract time series data (excluding mask) xi = x[i, :vl, :1] # Time-series data total_padded_length = pc * self.patch_size padding_length = total_padded_length - vl # Create position indices: real positions for actual data, special index for padding position_indices = torch.arange(vl, device=x.device) if padding_length > 0: # Pad with last value last_value = xi[-1:, :] padding = last_value.repeat(padding_length, 1) xi = torch.cat([xi, padding], dim=0) # Use special padding index for padding positions padding_positions = torch.full((padding_length,), self.padding_idx, device=x.device) position_indices = torch.cat([position_indices, padding_positions], dim=0)
# Reshape to patches xi = xi.reshape(pc, self.patch_size) # (num_patches, patch_size) position_indices = position_indices.reshape(pc, self.patch_size) # (num_patches, patch_size)
if self.use_position_embedding: # Collect position indices instead of calling embedding immediately all_position_indices.append(position_indices) patch_info_list.append({ 'xi': xi, 'pc': pc, 'sample_idx': i }) elif self.use_position_idx: # Normalize position indices pos_indices = torch.arange(vl, device=x.device).unsqueeze(1) pos_indices = pos_indices / max(1, valid_lengths.max().item() - 1) if padding_length > 0: # Use -1 for padding positions padding_indices = torch.full((padding_length, 1), -1, device=x.device) pos_indices = torch.cat([pos_indices, padding_indices], dim=0) # Combine time series data with position indices xi_combined = torch.cat([xi.reshape(-1, 1), pos_indices], dim=1) patch_input = xi_combined.reshape(pc, self.patch_size * 2) patches_list.append(patch_input) else: # No position embedding, use raw patches patch_input = xi patches_list.append(patch_input)
# Batch process position embeddings if needed if self.use_position_embedding and all_position_indices: # Concatenate all position indices for batch embedding lookup batch_position_indices = torch.cat(all_position_indices, dim=0) # print(f"{x.shape=}, {x.device=}, {len(all_position_indices)=}, {batch_position_indices=}") batch_pos_emb = self.position_embedding(batch_position_indices) # Single embedding call # Split embeddings back and create patch inputs emb_start_idx = 0 for patch_info in patch_info_list: xi = patch_info['xi'] pc = patch_info['pc'] # Extract corresponding embeddings pos_emb = batch_pos_emb[emb_start_idx:emb_start_idx + pc] emb_start_idx += pc # Flatten and concatenate xi = xi.unsqueeze(-1) # (num_patches, patch_size, 1) patch_input = torch.cat([ xi.flatten(1), # (num_patches, patch_size) pos_emb.flatten(1) # (num_patches, patch_size * embedding_dim) ], dim=1) patches_list.append(patch_input)
# Process all patches through MLP if patches_list: x_patches = torch.cat(patches_list, dim=0) x = self.mlp(x_patches) else: # Handle empty case x = torch.empty(0, self.hidden_size, device=x.device)
return x, patch_cnt
@dataclassclass Qwen3TSCausalLMOutputWithPast(CausalLMOutputWithPast): """ Output type of Qwen3TSForCausalLM that includes additional fields for timeseries processing. Args: loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Language modeling loss (for next-token prediction). logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed): Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*): The attention mask used in the forward pass, potentially expanded to accommodate timeseries patches. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. new_token_positions (`torch.LongTensor` of shape `(batch_size, num_new_tokens)`, *optional*): Positions where new tokens (not from timeseries) are located in the expanded sequence. """ last_hidden_state: Optional[torch.FloatTensor] = None attention_mask: Optional[torch.FloatTensor] = None labels: Optional[torch.LongTensor] = None new_token_positions: Optional[torch.LongTensor] = None
class Qwen3TSGenerationMixin(GenerationMixin): """ Generation mixin for Qwen3 models with timeseries support. This mixin handles the special case where timeseries embeddings expand the sequence length during the first forward pass, requiring special attention mask management. """ def prepare_inputs_for_generation( self, input_ids: torch.LongTensor, past_key_values: Optional[Cache] = None, attention_mask: Optional[torch.LongTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, cache_position: Optional[torch.LongTensor] = None, timeseries: Optional[torch.FloatTensor] = None, **kwargs, ) -> Dict[str, Any]: """ Prepare inputs for generation with timeseries support. Timeseries are only processed during the first forward pass. In subsequent generation steps, they are already embedded in the past_key_values. """ # Check if we have timeseries data has_ts = timeseries is not None and len(timeseries) > 0 # Handle timeseries for generation with past_key_values if has_ts and past_key_values is not None: # Get the number of tokens already processed if isinstance(past_key_values, Cache): if hasattr(past_key_values, 'seen_tokens'): past_length = past_key_values.seen_tokens else: past_length = past_key_values.get_seq_length() else: past_length = past_key_values[0][0].shape[2] if past_key_values[0] is not None else 0 # If we have processed tokens, timeseries have already been embedded if past_length > 0: # Only keep the last token for next token prediction input_ids = input_ids[:, -1:] # Clear timeseries as they've been processed timeseries = None has_ts = False # Call parent's prepare_inputs_for_generation to handle all standard logic # print(f"[debug] {input_ids.shape=}, {attention_mask.shape=}, {cache_position.max()=}, {past_length=}, {has_ts=}") model_inputs = super().prepare_inputs_for_generation( input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, inputs_embeds=inputs_embeds, cache_position=cache_position, **kwargs ) # Add timeseries to model inputs model_inputs["timeseries"] = timeseries return model_inputs def _update_model_kwargs_for_generation( self, outputs: ModelOutput, model_kwargs: Dict[str, Any], is_encoder_decoder: bool = False, num_new_tokens: int = 1, ) -> Dict[str, Any]: """ Update model keyword arguments for generation, handling attention mask from outputs. This is necessary because timeseries processing can expand the sequence length, and we need to use the expanded attention_mask from the model outputs. """ # Handle special case: use attention_mask from outputs if available # This is crucial for timeseries models where the sequence length is expanded if hasattr(outputs, "attention_mask") and outputs.attention_mask is not None: model_kwargs["attention_mask"] = outputs.attention_mask # Call parent's implementation for standard updates model_kwargs = super()._update_model_kwargs_for_generation( outputs=outputs, model_kwargs=model_kwargs, is_encoder_decoder=is_encoder_decoder, num_new_tokens=num_new_tokens, ) return model_kwargs def generate( self, inputs: Optional[torch.Tensor] = None, timeseries: Optional[torch.FloatTensor] = None, generation_config=None, **kwargs, ): """ Generate sequences with timeseries support. Args: inputs: Input token ids timeseries: Optional timeseries data to be processed in the first forward pass generation_config: Generation configuration **kwargs: Additional keyword arguments for generation """ # Add timeseries to kwargs if provided if timeseries is not None: kwargs["timeseries"] = timeseries # Call parent's generate method return super().generate( inputs=inputs, generation_config=generation_config, **kwargs, ) def _validate_model_kwargs(self, model_kwargs: Dict[str, Any]) -> None: """ Validate model kwargs, allowing timeseries as a valid argument. """ # Remove timeseries from model_kwargs temporarily for validation timeseries = model_kwargs.pop("timeseries", None) # Call parent's validation super()._validate_model_kwargs(model_kwargs) # Restore timeseries if timeseries is not None: model_kwargs["timeseries"] = timeseries
class Qwen3TSPreTrainedModel(Qwen3PreTrainedModel): config_class = Qwen3TSConfig
@auto_docstringclass Qwen3TSForCausalLM(Qwen3TSPreTrainedModel, Qwen3TSGenerationMixin): _tied_weights_keys = ["lm_head.weight"] _tp_plan = {"lm_head": "colwise_rep"} _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config): super().__init__(config) self.model = Qwen3Model(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# TS embedding self.ts_encoder = TimeSeriesEmbedding(config.ts)
# Initialize weights and apply final processing 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 merge_ununiform_ts(self, time_series_features, inputs_embeds, input_ids, attention_mask, labels, patch_cnt): """Merge the TS patch embeddings into the token sequence; rows may hold different patch counts.""" batch_size, sequence_length = input_ids.shape device = input_ids.device
_left_padding = torch.any(attention_mask[:, 0] == 0) _right_padding = torch.any(attention_mask[:, -1] == 0) if _left_padding and _right_padding: raise ValueError(f"both side of attention_mask has zero, invalid. {attention_mask}") left_padding = bool(_left_padding and not _right_padding)
start_mask = input_ids == self.config.ts_token_start_index marker_mask = start_mask | (input_ids == self.config.ts_token_end_index) real = attention_mask.bool()
patch_cnt = patch_cnt.to(device) num_ts_row = start_mask.sum(dim=-1) # series per row n_series = int(num_ts_row.sum()) if n_series != patch_cnt.numel(): raise ValueError( f"{n_series} <ts> markers in the batch but {patch_cnt.numel()} patch counts" )
# Slots each row gains: a series takes patch_cnt slots and already owns its two markers. row_of_series = torch.repeat_interleave(torch.arange(batch_size, device=device), num_ts_row) patches_row = torch.zeros(batch_size, dtype=torch.long, device=device).index_add_( 0, row_of_series, patch_cnt ) num_total_patches = patches_row - 2 * num_ts_row
grow = torch.zeros(batch_size, sequence_length, dtype=torch.long, device=device) grow[start_mask] = patch_cnt - 2 # start_mask.nonzero() is row-major, matching patch_cnt
# Destination of every token within its own row. rank = (real.long().cumsum(dim=-1) - 1).clamp(min=0) # real tokens before this one grow_real = grow * real growth_before = grow_real.cumsum(dim=-1) - grow_real # exclusive prefix sum dest = rank + growth_before
own_len = real.sum(dim=-1) + num_total_patches # expanded length per row max_embed_dim = sequence_length + int(num_total_patches.max()) offset = (max_embed_dim - own_len) if left_padding else torch.zeros_like(own_len) dest = dest + offset[:, None] # the single padding step
# Text tokens; the markers and padding are not placed. final_embedding = torch.zeros( batch_size, max_embed_dim, inputs_embeds.size(-1), dtype=inputs_embeds.dtype, device=inputs_embeds.device, ) text_sel = real & ~marker_mask t_batch, t_pos = text_sel.nonzero(as_tuple=True) final_embedding[t_batch, dest[t_batch, t_pos]] = inputs_embeds[t_batch, t_pos]
final_labels = None if labels is not None: final_labels = torch.full( (batch_size, max_embed_dim), self.config.ignore_index, dtype=labels.dtype, device=labels.device, ) final_labels[t_batch, dest[t_batch, t_pos]] = labels[t_batch, t_pos]
# Patches: one contiguous block per series, starting at its <ts> destination. s_batch, s_pos = start_mask.nonzero(as_tuple=True) block_start = dest[s_batch, s_pos] total_patches = int(patch_cnt.sum()) if time_series_features.shape[0] != total_patches: raise ValueError( f"The input provided to the model are wrong. patch_cnt sums to {total_patches} " f"but {time_series_features.shape[0]} time-series features were given. " "This prevents correct indexing and breaks batch generation." ) series_id = torch.repeat_interleave(torch.arange(n_series, device=device), patch_cnt) within = torch.arange(total_patches, device=device) - torch.repeat_interleave( patch_cnt.cumsum(0) - patch_cnt, patch_cnt ) final_embedding[s_batch[series_id], block_start[series_id] + within] = ( time_series_features.contiguous().to(final_embedding.dtype) )
# Attention mask, positions and the input -> expanded index map. ar = torch.arange(max_embed_dim, device=device)[None, :] final_attention_mask = ( (ar >= offset[:, None]) & (ar < (offset + own_len)[:, None]) ).to(attention_mask.dtype)
position_ids = (final_attention_mask.cumsum(-1) - 1).masked_fill_( final_attention_mask == 0, 1 ) # As in ChatTS, a <ts> marker maps to the end of its patch block. new_token_positions = (dest + grow_real).masked_fill(attention_mask == 0, -1)
return final_embedding, final_attention_mask, position_ids, final_labels, new_token_positions
def _merge_input_ids_with_time_series_features(self, time_series_features, inputs_embeds, input_ids, attention_mask, labels, patch_cnt): """ChatTS's name for :meth:`merge_ununiform_ts`.""" return self.merge_ununiform_ts( time_series_features, inputs_embeds, input_ids, attention_mask, labels, patch_cnt )
@can_return_tuple def forward( self, input_ids: Optional[torch.LongTensor] = None, timeseries: torch.FloatTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs, ) -> Qwen3TSCausalLMOutputWithPast: r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*): Pre-computed hidden-states (key and values in the attention blocks). inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*): Indices depicting the position of the input sequence tokens in the sequence. timeseries (`torch.FloatTensor` of shape `(batch_size, num_patches, patch_size)`, *optional*): Timeseries data to be encoded and merged with text embeddings. Returns: [`Qwen3TSCausalLMOutputWithPast`] or `tuple(torch.FloatTensor)`: The model outputs with potential timeseries-expanded attention mask. """
# if input_ids is not None and timeseries is not None: # # Print the input ts # print("=================================================================") # print("Timeseries shape:", timeseries.shape) # print("=================================================================\n\n") # else: # print("Time series is None!!!!")
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 )
if inputs_embeds is None: inputs_embeds = self.get_input_embeddings()(input_ids)
if timeseries is not None and timeseries.shape[0] > 0: # use_cache = False # print(f"timeseries shape: {timeseries.shape=}, {input_ids.shape=}") ts_features, patch_cnt = self.ts_encoder(timeseries) inputs_embeds = inputs_embeds.to(ts_features.dtype) # if str(input_ids.device) == 'cuda:0': # print(f"-------------------------------------------------------\n[before] {input_ids.shape=}, timeseries={timeseries.shape if timeseries is not None else None}, {attention_mask.sum(-1)=}") inputs_embeds, attention_mask, position_ids, labels, new_token_positions = self.merge_ununiform_ts( ts_features, inputs_embeds, input_ids, attention_mask, labels, patch_cnt ) if cache_position is not None: cache_position = torch.arange( attention_mask.size(-1) - inputs_embeds.size(1), attention_mask.size(-1), device=inputs_embeds.device )
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) # if str(input_ids.device) == 'cuda:0': # print(f"[after] {inputs_embeds.shape=}, {attention_mask.sum(-1)=}, {position_ids.max(-1)=}, {cache_position.max().item()=}") outputs: BaseModelOutputWithPast = self.model( attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, cache_position=cache_position, **kwargs, )
hidden_states = outputs.last_hidden_state # Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :])
loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs) # print(f"{logits.shape=}, {hidden_states.shape=}, {slice_indices=}, {logits_to_keep=}, labels={(labels != self.config.ignore_index).sum() if labels is not None else None}, {loss=}, {torch.sum(torch.isnan(logits))=}, {torch.sum(torch.isinf(logits))=}, {torch.sum(torch.isnan(hidden_states))=}, {torch.sum(torch.isinf(hidden_states))=}")
return Qwen3TSCausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, last_hidden_state=hidden_states, hidden_states=outputs.hidden_states, attentions=outputs.attentions, attention_mask=attention_mask, labels=labels, new_token_positions=new_token_positions if timeseries is not None and timeseries.shape[0] > 0 else None, )
__all__ = [ "Qwen3TSForCausalLM"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224# coding=utf-8# Copyright 2024 Tsinghua University and ByteDance.## Licensed under the MIT License (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://opensource.org/license/mit## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import numpy as npfrom typing import List, Union, Tuple, Optionalimport torch
from transformers.feature_extraction_utils import BatchFeaturefrom transformers.processing_utils import ProcessorMixinfrom transformers.tokenization_utils_base import PaddingStrategy
def sp_encoding(timeseries: np.ndarray, eots_token: bool = True) -> Tuple[np.ndarray, str, dict]: """ Encodes a time series with scalar normalization.
Args: timeseries (np.ndarray): The raw time series data (1D or 2D).
Returns: result_timeseries (np.ndarray): The encoded time series, shape [seq_len, 1]. prompt (str): The placeholder string with offset and scaling info. metadata (dict): Metadata containing the offset and scaling factor. """ timeseries = np.array(timeseries) mean = np.mean(timeseries) scaled_timeseries = timeseries - mean scale_factor = 1.0 if np.any(np.abs(scaled_timeseries) >= 3.0): scale_factor = np.max(np.abs(scaled_timeseries)) / 3.0 scaled_timeseries /= scale_factor
prompt = f"[offset={-mean:.4f}|scaling={scale_factor:.4f}|length={len(timeseries)}|max={max(timeseries):.4f}|min={min(timeseries):.4f}|left={timeseries[0]:.4f}|right={timeseries[-1]:.4f}]<ts>" if eots_token: prompt += '<ts/>'
result_timeseries = np.stack([scaled_timeseries, np.ones_like(scaled_timeseries)], axis=-1).reshape(-1, 1)
return result_timeseries, prompt, {"offset": float(-mean), "scale_factor": float(scale_factor)}
class Qwen3TSProcessor(ProcessorMixin): """ A processor for ChatTS that integrates text prompt processing and time series encoding. """
attributes = ["tokenizer"] feature_extractor_class = None # You can add a feature extractor if needed tokenizer_class = "AutoTokenizer"
def __init__(self, tokenizer=None, chat_template=None, **kwargs): """ Args: tokenizer: An optional tokenizer to process text prompts. """ if chat_template is None and tokenizer is not None and tokenizer.chat_template is not None: chat_template = tokenizer.chat_template self.chat_template = chat_template
super().__init__(tokenizer=tokenizer, chat_template=chat_template, **kwargs)
def __call__( self, text: Union[str, List[str]], timeseries: Optional[List[List[np.ndarray]]] = None, padding: Union[bool, str, PaddingStrategy] = False, padding_side: str = 'left', vllm_flag: bool = False, tokenize: bool = True, **kwargs, ) -> BatchFeature: """ Encodes a prompt and its associated time series.
Args: prompt (List[str]): The input prompt containing <ts><ts/> placeholders. timeseries (List[np.ndarray]): A list of time series matched to placeholders in the prompt. padding (bool or str or PaddingStrategy, optional): Passed to the tokenizer for text padding. return_tensors (str, optional): "pt" to return PyTorch tensors; None to return NumPy arrays. **kwargs: Additional tokenizer parameters.
Returns: BatchFeature: Contains processed prompt, encoded time series, and tokenizer outputs. """ if type(text) == str: text = [text] if timeseries is None: timeseries = []
reconstructed_prompts = [] concatenated_ts = None ts_tokens = []
if vllm_flag: # All prompt modifications have to be done inside of the vLLM # to work correctly with its caching mechanism. reconstructed_prompts = text # Process timeseries data encoded_ts_arrays = [] for ts in timeseries: # Get the normalized data and prompt text encoded_ts, ts_prompt, _ = sp_encoding(ts, eots_token=False) # Tokenize the ts_prompt and add to the tokens list if self.tokenizer is not None: tokens = self.tokenizer.encode(ts_prompt, add_special_tokens=False) ts_tokens.append(tokens) encoded_ts_arrays.append(encoded_ts[None, ...]) else: encoded_ts_arrays = [] total_ts_cnt = 0 for idx, prompt in enumerate(text): # Split prompt by <ts><ts/> placeholders last_ts_cnt = total_ts_cnt prompt_segments = prompt.split("<ts><ts/>") total_ts_cnt = total_ts_cnt + len(prompt_segments) - 1
# Encode each time series and rebuild the prompt reconstructed_prompt = prompt_segments[0]
for i, ts in enumerate(timeseries[last_ts_cnt:total_ts_cnt]): encoded_ts, ts_prompt, _ = sp_encoding(ts, eots_token=not vllm_flag) reconstructed_prompt += ts_prompt + prompt_segments[i + 1] # Ensure time series shape [1, seq_len, feature_dim] for batch concatenation encoded_ts_arrays.append(encoded_ts[None, ...])
reconstructed_prompts.append(reconstructed_prompt)
if len(timeseries) != len(encoded_ts_arrays): raise ValueError( f"Mismatch between <ts><ts/> placeholders ({total_ts_cnt}) " f"and time series ({len(encoded_ts_arrays)})." )
if len(encoded_ts_arrays) > 0: # Pad time series to the same length max_length = max(ts.shape[1] for ts in encoded_ts_arrays) padded_ts_arrays = [ np.pad(ts, ((0, 0), (0, max_length - ts.shape[1]), (0, 0)), mode="constant", constant_values=0.0) for ts in encoded_ts_arrays ] concatenated_ts = np.concatenate(padded_ts_arrays, axis=0) # Shape: [batch_size, max_length, feature_dim] # Convert to torch concatenated_ts = torch.from_numpy(concatenated_ts).half()
# Tokenize the processed prompt tokenizer_outputs = {} if tokenize and self.tokenizer is not None: tokenizer_outputs = self.tokenizer(reconstructed_prompts, padding=padding, padding_side=padding_side, **kwargs) else: tokenizer_outputs = {"text": reconstructed_prompts}
# Create the final output outputs = tokenizer_outputs if vllm_flag: outputs["timeseries"] = zip(ts_tokens, encoded_ts_arrays) elif concatenated_ts is not None: outputs["timeseries"] = concatenated_ts
return BatchFeature(data=outputs)
def encode_timeseries( self, timeseries: Optional[List[List[np.ndarray]]] = None, ) -> np.ndarray: if timeseries is None: timeseries = []
concatenated_ts = None encoded_ts_arrays = []
for i, ts in enumerate(timeseries): encoded_ts, _, _ = sp_encoding(ts) # Ensure time series shape [1, seq_len, feature_dim] for batch concatenation encoded_ts_arrays.append(encoded_ts[None, ...])
if len(encoded_ts_arrays) > 0: # Pad time series to the same length max_length = max(ts.shape[1] for ts in encoded_ts_arrays) padded_ts_arrays = [ np.pad(ts, ((0, 0), (0, max_length - ts.shape[1]), (0, 0)), mode="constant", constant_values=0.0) for ts in encoded_ts_arrays ] concatenated_ts = np.concatenate(padded_ts_arrays, axis=0) # Shape: [batch_size, max_length, feature_dim] # Convert to torch concatenated_ts = torch.from_numpy(concatenated_ts).half()
return concatenated_ts
@property def model_input_names(self): """ Define the input names expected by the model. """ tokenizer_input_names = [] if self.tokenizer and hasattr(self.tokenizer, "model_input_names"): tokenizer_input_names = self.tokenizer.model_input_names return list(dict.fromkeys(["processed_prompt", "time_series"] + tokenizer_input_names))
def batch_decode(self, *args, **kwargs): """ This method forwards all its arguments to Qwen3TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please refer to the docstring of this method for more information. """ return self.tokenizer.batch_decode(*args, **kwargs)
def decode(self, *args, **kwargs): """ This method forwards all its arguments to Qwen3TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to the docstring of this method for more information. """ return self.tokenizer.decode(*args, **kwargs)123456{ "auto_map": { "AutoProcessor": "processing_qwen3_ts.Qwen3TSProcessor" }, "processor_class": "Qwen3TSProcessor"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424{ "metadata": { "total_parameters": 343040, "total_size": 16554031136 }, "weight_map": { "codi_projection.1.bias": "pytorch_model-00004-of-00004.bin", "codi_projection.1.weight": "pytorch_model-00004-of-00004.bin", "codi_projection.3.bias": "pytorch_model-00004-of-00004.bin", "codi_projection.3.weight": "pytorch_model-00004-of-00004.bin", "codi_projection.ln.bias": "pytorch_model-00004-of-00004.bin", "codi_projection.ln.weight": "pytorch_model-00004-of-00004.bin", "lm_head.weight": "pytorch_model-00004-of-00004.bin", "model.embed_tokens.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.10.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.2.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.20.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.22.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.22.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.22.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.22.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.22.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.22.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.22.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.22.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.22.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.22.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.22.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.23.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.3.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.30.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.35.input_layernorm.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.mlp.down_proj.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.mlp.gate_proj.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.mlp.up_proj.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.post_attention_layernorm.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.self_attn.k_norm.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.35.self_attn.o_proj.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.self_attn.q_norm.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.35.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.4.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.9.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.9.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.9.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.9.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.9.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.9.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.9.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.9.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.9.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.9.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.9.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.norm.weight": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.0.bias": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.0.weight": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.2.bias": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.2.weight": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.4.bias": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.4.weight": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.6.bias": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.6.weight": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.8.bias": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.8.weight": "pytorch_model-00004-of-00004.bin", "ts_encoder.position_embedding.weight": "pytorch_model-00004-of-00004.bin" }}1234567891011121314151617181920{ "additional_special_tokens": [ "<ts>", "<ts/>" ], "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 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265{ "add_bos_token": false, "add_prefix_space": false, "added_tokens_decoder": { "151643": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151644": { "content": "<|im_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151645": { "content": "<|im_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151646": { "content": "<|object_ref_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151647": { "content": "<|object_ref_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151648": { "content": "<|box_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151649": { "content": "<|box_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151650": { "content": "<|quad_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151651": { "content": "<|quad_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151652": { "content": "<|vision_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151653": { "content": "<|vision_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151654": { "content": "<|vision_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151655": { "content": "<|image_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151656": { "content": "<|video_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151657": { "content": "<tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151658": { "content": "</tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151659": { "content": "<|fim_prefix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151660": { "content": "<|fim_middle|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151661": { "content": "<|fim_suffix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151662": { "content": "<|fim_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151663": { "content": "<|repo_name|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151664": { "content": "<|file_sep|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151665": { "content": "<tool_response>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151666": { "content": "</tool_response>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151667": { "content": "<think>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151668": { "content": "</think>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151669": { "content": "<ts>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151670": { "content": "<ts/>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151671": { "content": "<|bot|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151672": { "content": "<|eot|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true } }, "additional_special_tokens": [ "<ts>", "<ts/>" ], "auto_map": { "AutoProcessor": "processing_qwen3_ts.Qwen3TSProcessor" }, "bos_token": null, "clean_up_tokenization_spaces": false, "eos_token": "<|im_end|>", "errors": "replace", "extra_special_tokens": {}, "model_max_length": 131072, "pad_token": "<|endoftext|>", "padding_side": "right", "processor_class": "Qwen3TSProcessor", "split_special_tokens": false, "tokenizer_class": "Qwen2Tokenizer", "unk_token": null}1234567891011121314151617181920212223242526272829303132{ "</think>": 151668, "</tool_call>": 151658, "</tool_response>": 151666, "<think>": 151667, "<tool_call>": 151657, "<tool_response>": 151665, "<ts/>": 151670, "<ts>": 151669, "<|bot|>": 151671, "<|box_end|>": 151649, "<|box_start|>": 151648, "<|endoftext|>": 151643, "<|eot|>": 151672, "<|file_sep|>": 151664, "<|fim_middle|>": 151660, "<|fim_pad|>": 151662, "<|fim_prefix|>": 151659, "<|fim_suffix|>": 151661, "<|im_end|>": 151645, "<|im_start|>": 151644, "<|image_pad|>": 151655, "<|object_ref_end|>": 151647, "<|object_ref_start|>": 151646, "<|quad_end|>": 151651, "<|quad_start|>": 151650, "<|repo_name|>": 151663, "<|video_pad|>": 151656, "<|vision_end|>": 151653, "<|vision_pad|>": 151654, "<|vision_start|>": 151652}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889{%- if tools %} {{- '<|im_start|>system\n' }} {%- if messages[0].role == 'system' %} {{- messages[0].content + '\n\n' }} {%- 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' }} {%- 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 message.content is string 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.content is string %} {%- set content = message.content %} {%- else %} {%- set content = '' %} {%- endif %} {%- if (message.role == "user") or (message.role == "system" and not loop.first) %} {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} {%- elif message.role == "assistant" %} {%- set reasoning_content = '' %} {%- if message.reasoning_content is string %} {%- set reasoning_content = message.reasoning_content %} {%- else %} {%- if '</think>' in content %} {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %} {%- set content = content.split('</think>')[-1].lstrip('\n') %} {%- endif %} {%- endif %} {%- if loop.index0 > ns.last_query_index %} {%- if loop.last or (not loop.last and reasoning_content) %} {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }} {%- else %} {{- '<|im_start|>' + message.role + '\n' + content }} {%- endif %} {%- else %} {{- '<|im_start|>' + message.role + '\n' + content }} {%- endif %} {%- 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' }} {{- 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' }} {%- if enable_thinking is defined and enable_thinking is false %} {{- '<think>\n\n</think>\n\n' }} {%- endif %}{%- endif %}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990{ "architectures": [ "Qwen3TSForCausalLM" ], "attention_bias": false, "attention_dropout": 0.0, "auto_map": { "AutoConfig": "configuration_qwen3_ts.Qwen3TSConfig", "AutoModel": "modeling_qwen3_ts.Qwen3TSForCausalLM", "AutoModelForCausalLM": "modeling_qwen3_ts.Qwen3TSForCausalLM", "AutoProcessor": "processing_qwen3_ts.Qwen3TSProcessor" }, "bos_token_id": 151643, "eos_token_id": 151645, "head_dim": 128, "hidden_act": "silu", "hidden_size": 4096, "ignore_index": -100, "initializer_range": 0.02, "intermediate_size": 12288, "layer_types": [ "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention" ], "max_position_embeddings": 40960, "max_window_layers": 36, "model_type": "qwen3ts", "num_attention_heads": 32, "num_hidden_layers": 36, "num_key_value_heads": 8, "pad_token_id": 151643, "rms_norm_eps": 1e-06, "rope_scaling": null, "rope_theta": 1000000, "sliding_window": null, "tie_word_embeddings": false, "torch_dtype": "bfloat16", "transformers_version": "4.55.4", "ts": { "embedding_dim": 16, "hidden_size": 4096, "max_length": 32768, "max_sequence_length": 8192, "num_features": 2, "num_layers": 5, "patch_size": 60, "use_layer_norm": false, "use_position_embedding": true, "use_position_idx": false }, "ts_token_end_index": 151670, "ts_token_start_index": 151669, "use_cache": false, "use_sliding_window": false, "vocab_size": 151936}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225# coding=utf-8# Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Qwen3 model configuration"""
from transformers.configuration_utils import PretrainedConfigfrom transformers.modeling_rope_utils import rope_config_validationfrom transformers.utils import logging
logger = logging.get_logger(__name__)
class Qwen3TSConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`Qwen3Model`]. It is used to instantiate a Qwen3 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of Qwen3-8B [Qwen/Qwen3-8B](https://huggingface.co/Qwen/Qwen3-8B).
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.
Args: vocab_size (`int`, *optional*, defaults to 151936): Vocabulary size of the Qwen3 model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`Qwen3Model`] hidden_size (`int`, *optional*, defaults to 4096): Dimension of the hidden representations. intermediate_size (`int`, *optional*, defaults to 22016): Dimension of the MLP representations. num_hidden_layers (`int`, *optional*, defaults to 32): Number of hidden layers in the Transformer encoder. num_attention_heads (`int`, *optional*, defaults to 32): Number of attention heads for each attention layer in the Transformer encoder. num_key_value_heads (`int`, *optional*, defaults to 32): This is the number of key_value heads that should be used to implement Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details, check out [this paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`. head_dim (`int`, *optional*, defaults to 128): The attention head dimension. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`): The non-linear activation function (function or string) in the decoder. max_position_embeddings (`int`, *optional*, defaults to 32768): The maximum sequence length that this model might ever be used with. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. rms_norm_eps (`float`, *optional*, defaults to 1e-06): The epsilon used by the rms normalization layers. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True`. tie_word_embeddings (`bool`, *optional*, defaults to `False`): Whether the model's input and output word embeddings should be tied. rope_theta (`float`, *optional*, defaults to 10000.0): The base period of the RoPE embeddings. rope_scaling (`Dict`, *optional*): Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value accordingly. Expected contents: `rope_type` (`str`): The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope', 'llama3'], with 'default' being the original RoPE implementation. `factor` (`float`, *optional*): Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In most scaling types, a `factor` of x will enable the model to handle sequences of length x * original maximum pre-trained length. `original_max_position_embeddings` (`int`, *optional*): Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during pretraining. `attention_factor` (`float`, *optional*): Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention computation. If unspecified, it defaults to value recommended by the implementation, using the `factor` field to infer the suggested value. `beta_fast` (`float`, *optional*): Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear ramp function. If unspecified, it defaults to 32. `beta_slow` (`float`, *optional*): Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear ramp function. If unspecified, it defaults to 1. `short_factor` (`list[float]`, *optional*): Only used with 'longrope'. The scaling factor to be applied to short contexts (< `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 `long_factor` (`list[float]`, *optional*): Only used with 'longrope'. The scaling factor to be applied to long contexts (< `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 `low_freq_factor` (`float`, *optional*): Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE `high_freq_factor` (`float`, *optional*): Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`): Whether to use a bias in the query, key, value and output projection layers during self-attention. use_sliding_window (`bool`, *optional*, defaults to `False`): Whether to use sliding window attention. sliding_window (`int`, *optional*, defaults to 4096): Sliding window attention (SWA) window size. If not specified, will default to `4096`. max_window_layers (`int`, *optional*, defaults to 28): The number of layers using full attention. The first `max_window_layers` layers will use full attention, while any additional layer afterwards will use SWA (Sliding Window Attention). layer_types (`list`, *optional*): Attention pattern for each layer. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities.
```python >>> from transformers import Qwen3Model, Qwen3Config
>>> # Initializing a Qwen3 style configuration >>> configuration = Qwen3Config()
>>> # Initializing a model from the Qwen3-8B style configuration >>> model = Qwen3Model(configuration)
>>> # Accessing the model configuration >>> configuration = model.config ```"""
model_type = "qwen3ts" keys_to_ignore_at_inference = ["past_key_values"]
# Default tensor parallel plan for base model `Qwen3` base_model_tp_plan = { "layers.*.self_attn.q_proj": "colwise", "layers.*.self_attn.k_proj": "colwise", "layers.*.self_attn.v_proj": "colwise", "layers.*.self_attn.o_proj": "rowwise", "layers.*.mlp.gate_proj": "colwise", "layers.*.mlp.up_proj": "colwise", "layers.*.mlp.down_proj": "rowwise", } base_model_pp_plan = { "embed_tokens": (["input_ids"], ["inputs_embeds"]), "layers": (["hidden_states", "attention_mask"], ["hidden_states"]), "norm": (["hidden_states"], ["hidden_states"]), }
def __init__( self, vocab_size=151936, hidden_size=4096, intermediate_size=22016, num_hidden_layers=32, num_attention_heads=32, num_key_value_heads=32, head_dim=128, hidden_act="silu", max_position_embeddings=32768, initializer_range=0.02, rms_norm_eps=1e-6, use_cache=True, tie_word_embeddings=False, rope_theta=10000.0, rope_scaling=None, attention_bias=False, use_sliding_window=False, sliding_window=4096, max_window_layers=28, layer_types=None, attention_dropout=0.0, **kwargs, ): self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.use_sliding_window = use_sliding_window self.sliding_window = sliding_window if self.use_sliding_window else None self.max_window_layers = max_window_layers
# for backward compatibility if num_key_value_heads is None: num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads self.head_dim = head_dim self.hidden_act = hidden_act self.initializer_range = initializer_range self.rms_norm_eps = rms_norm_eps self.use_cache = use_cache self.rope_theta = rope_theta self.rope_scaling = rope_scaling self.attention_bias = attention_bias self.attention_dropout = attention_dropout # Validate the correctness of rotary position embeddings parameters # BC: if there is a 'type' field, move it to 'rope_type'. if self.rope_scaling is not None and "type" in self.rope_scaling: self.rope_scaling["rope_type"] = self.rope_scaling["type"] rope_config_validation(self)
self.layer_types = layer_types if self.layer_types is None: self.layer_types = [ "sliding_attention" if self.sliding_window is not None and i >= self.max_window_layers else "full_attention" for i in range(self.num_hidden_layers) ]
super().__init__( tie_word_embeddings=tie_word_embeddings, **kwargs, )
__all__ = ["Qwen3TSConfig"]12345678910111213{ "bos_token_id": 151643, "do_sample": true, "eos_token_id": [ 151645, 151643 ], "pad_token_id": 151643, "temperature": 0.6, "top_k": 20, "top_p": 0.95, "transformers_version": "4.55.4"}123456789101112{ "stage": "lapras", "template": "chatts", "ts_patch_size": 60, "answer_anchor": "Answer:", "use_cot": null, "num_latent": 6, "projection": { "projection_dim": 2048 }, "remove_eos": true}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601# Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
from typing import Callable, Optional, Union
import torchfrom torch import nnfrom dataclasses import dataclass
from transformers.cache_utils import Cachefrom transformers.generation import GenerationMixinfrom transformers.modeling_flash_attention_utils import FlashAttentionKwargsfrom transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast)from transformers.models.qwen3.modeling_qwen3 import Qwen3PreTrainedModel, Qwen3Modelfrom transformers.modeling_utils import PreTrainedModelfrom transformers.processing_utils import Unpackfrom transformers.utils import auto_docstring, can_return_tuple, logging, ModelOutputfrom .configuration_qwen3_ts import Qwen3TSConfigfrom typing import Any, Dict
logger = logging.get_logger(__name__)
########################MLP TS Embedding#####################class TimeSeriesEmbedding(nn.Module): def __init__(self, config): super(TimeSeriesEmbedding, self).__init__() self.patch_size = config['patch_size'] self.num_layers = config['num_layers'] self.hidden_size = config['hidden_size'] self.num_features = config['num_features'] self.max_sequence_length = config['max_sequence_length'] # Maximum time series length self.use_position_embedding = config.get('use_position_embedding', False) self.use_position_idx = config.get('use_position_idx', False) self.use_layer_norm = config.get('use_layer_norm', False) self.embedding_dim = config.get('embedding_dim', 16) # Embedding dimension if self.use_position_embedding: # Extended vocabulary: [0, max_sequence_length) for real positions, max_sequence_length for padding self.position_embedding = nn.Embedding(self.max_sequence_length + 1, self.embedding_dim) self.padding_idx = self.max_sequence_length # Special index for padding input_size = 1 * self.patch_size + self.embedding_dim * self.patch_size elif self.use_position_idx: input_size = 2 * self.patch_size else: input_size = 1 * self.patch_size # Build MLP layers layers = [] for _ in range(self.num_layers - 1): layers.append(nn.Linear(input_size, self.hidden_size)) layers.append(nn.GELU()) input_size = self.hidden_size
layers.append(nn.Linear(input_size, self.hidden_size)) if self.use_layer_norm: layers.append(nn.LayerNorm(self.hidden_size))
self.mlp = nn.Sequential(*layers)
def forward(self, x: torch.Tensor): batch_size = x.size(0) x = x.reshape(batch_size, -1, self.num_features)
# Extract mask and calculate valid lengths mask = x[:, :, -1].long() valid_lengths = mask.sum(dim=1).long() patch_cnt = (valid_lengths + self.patch_size - 1) // self.patch_size
patches_list = [] # Collect position indices for batch embedding lookup all_position_indices = [] patch_info_list = [] # Store metadata for each patch group for i in range(batch_size): vl = valid_lengths[i].item() pc = patch_cnt[i].item() if pc == 0: continue # Extract time series data (excluding mask) xi = x[i, :vl, :1] # Time-series data total_padded_length = pc * self.patch_size padding_length = total_padded_length - vl # Create position indices: real positions for actual data, special index for padding position_indices = torch.arange(vl, device=x.device) if padding_length > 0: # Pad with last value last_value = xi[-1:, :] padding = last_value.repeat(padding_length, 1) xi = torch.cat([xi, padding], dim=0) # Use special padding index for padding positions padding_positions = torch.full((padding_length,), self.padding_idx, device=x.device) position_indices = torch.cat([position_indices, padding_positions], dim=0)
# Reshape to patches xi = xi.reshape(pc, self.patch_size) # (num_patches, patch_size) position_indices = position_indices.reshape(pc, self.patch_size) # (num_patches, patch_size)
if self.use_position_embedding: # Collect position indices instead of calling embedding immediately all_position_indices.append(position_indices) patch_info_list.append({ 'xi': xi, 'pc': pc, 'sample_idx': i }) elif self.use_position_idx: # Normalize position indices pos_indices = torch.arange(vl, device=x.device).unsqueeze(1) pos_indices = pos_indices / max(1, valid_lengths.max().item() - 1) if padding_length > 0: # Use -1 for padding positions padding_indices = torch.full((padding_length, 1), -1, device=x.device) pos_indices = torch.cat([pos_indices, padding_indices], dim=0) # Combine time series data with position indices xi_combined = torch.cat([xi.reshape(-1, 1), pos_indices], dim=1) patch_input = xi_combined.reshape(pc, self.patch_size * 2) patches_list.append(patch_input) else: # No position embedding, use raw patches patch_input = xi patches_list.append(patch_input)
# Batch process position embeddings if needed if self.use_position_embedding and all_position_indices: # Concatenate all position indices for batch embedding lookup batch_position_indices = torch.cat(all_position_indices, dim=0) # print(f"{x.shape=}, {x.device=}, {len(all_position_indices)=}, {batch_position_indices=}") batch_pos_emb = self.position_embedding(batch_position_indices) # Single embedding call # Split embeddings back and create patch inputs emb_start_idx = 0 for patch_info in patch_info_list: xi = patch_info['xi'] pc = patch_info['pc'] # Extract corresponding embeddings pos_emb = batch_pos_emb[emb_start_idx:emb_start_idx + pc] emb_start_idx += pc # Flatten and concatenate xi = xi.unsqueeze(-1) # (num_patches, patch_size, 1) patch_input = torch.cat([ xi.flatten(1), # (num_patches, patch_size) pos_emb.flatten(1) # (num_patches, patch_size * embedding_dim) ], dim=1) patches_list.append(patch_input)
# Process all patches through MLP if patches_list: x_patches = torch.cat(patches_list, dim=0) x = self.mlp(x_patches) else: # Handle empty case x = torch.empty(0, self.hidden_size, device=x.device)
return x, patch_cnt
@dataclassclass Qwen3TSCausalLMOutputWithPast(CausalLMOutputWithPast): """ Output type of Qwen3TSForCausalLM that includes additional fields for timeseries processing. Args: loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Language modeling loss (for next-token prediction). logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed): Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*): The attention mask used in the forward pass, potentially expanded to accommodate timeseries patches. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. new_token_positions (`torch.LongTensor` of shape `(batch_size, num_new_tokens)`, *optional*): Positions where new tokens (not from timeseries) are located in the expanded sequence. """ last_hidden_state: Optional[torch.FloatTensor] = None attention_mask: Optional[torch.FloatTensor] = None labels: Optional[torch.LongTensor] = None new_token_positions: Optional[torch.LongTensor] = None
class Qwen3TSGenerationMixin(GenerationMixin): """ Generation mixin for Qwen3 models with timeseries support. This mixin handles the special case where timeseries embeddings expand the sequence length during the first forward pass, requiring special attention mask management. """ def prepare_inputs_for_generation( self, input_ids: torch.LongTensor, past_key_values: Optional[Cache] = None, attention_mask: Optional[torch.LongTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, cache_position: Optional[torch.LongTensor] = None, timeseries: Optional[torch.FloatTensor] = None, **kwargs, ) -> Dict[str, Any]: """ Prepare inputs for generation with timeseries support. Timeseries are only processed during the first forward pass. In subsequent generation steps, they are already embedded in the past_key_values. """ # Check if we have timeseries data has_ts = timeseries is not None and len(timeseries) > 0 # Handle timeseries for generation with past_key_values if has_ts and past_key_values is not None: # Get the number of tokens already processed if isinstance(past_key_values, Cache): if hasattr(past_key_values, 'seen_tokens'): past_length = past_key_values.seen_tokens else: past_length = past_key_values.get_seq_length() else: past_length = past_key_values[0][0].shape[2] if past_key_values[0] is not None else 0 # If we have processed tokens, timeseries have already been embedded if past_length > 0: # Only keep the last token for next token prediction input_ids = input_ids[:, -1:] # Clear timeseries as they've been processed timeseries = None has_ts = False # Call parent's prepare_inputs_for_generation to handle all standard logic # print(f"[debug] {input_ids.shape=}, {attention_mask.shape=}, {cache_position.max()=}, {past_length=}, {has_ts=}") model_inputs = super().prepare_inputs_for_generation( input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, inputs_embeds=inputs_embeds, cache_position=cache_position, **kwargs ) # Add timeseries to model inputs model_inputs["timeseries"] = timeseries return model_inputs def _update_model_kwargs_for_generation( self, outputs: ModelOutput, model_kwargs: Dict[str, Any], is_encoder_decoder: bool = False, num_new_tokens: int = 1, ) -> Dict[str, Any]: """ Update model keyword arguments for generation, handling attention mask from outputs. This is necessary because timeseries processing can expand the sequence length, and we need to use the expanded attention_mask from the model outputs. """ # Handle special case: use attention_mask from outputs if available # This is crucial for timeseries models where the sequence length is expanded if hasattr(outputs, "attention_mask") and outputs.attention_mask is not None: model_kwargs["attention_mask"] = outputs.attention_mask # Call parent's implementation for standard updates model_kwargs = super()._update_model_kwargs_for_generation( outputs=outputs, model_kwargs=model_kwargs, is_encoder_decoder=is_encoder_decoder, num_new_tokens=num_new_tokens, ) return model_kwargs def generate( self, inputs: Optional[torch.Tensor] = None, timeseries: Optional[torch.FloatTensor] = None, generation_config=None, **kwargs, ): """ Generate sequences with timeseries support. Args: inputs: Input token ids timeseries: Optional timeseries data to be processed in the first forward pass generation_config: Generation configuration **kwargs: Additional keyword arguments for generation """ # Add timeseries to kwargs if provided if timeseries is not None: kwargs["timeseries"] = timeseries # Call parent's generate method return super().generate( inputs=inputs, generation_config=generation_config, **kwargs, ) def _validate_model_kwargs(self, model_kwargs: Dict[str, Any]) -> None: """ Validate model kwargs, allowing timeseries as a valid argument. """ # Remove timeseries from model_kwargs temporarily for validation timeseries = model_kwargs.pop("timeseries", None) # Call parent's validation super()._validate_model_kwargs(model_kwargs) # Restore timeseries if timeseries is not None: model_kwargs["timeseries"] = timeseries
class Qwen3TSPreTrainedModel(Qwen3PreTrainedModel): config_class = Qwen3TSConfig
@auto_docstringclass Qwen3TSForCausalLM(Qwen3TSPreTrainedModel, Qwen3TSGenerationMixin): _tied_weights_keys = ["lm_head.weight"] _tp_plan = {"lm_head": "colwise_rep"} _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config): super().__init__(config) self.model = Qwen3Model(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# TS embedding self.ts_encoder = TimeSeriesEmbedding(config.ts)
# Initialize weights and apply final processing 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 merge_ununiform_ts(self, time_series_features, inputs_embeds, input_ids, attention_mask, labels, patch_cnt): """Merge the TS patch embeddings into the token sequence; rows may hold different patch counts.""" batch_size, sequence_length = input_ids.shape device = input_ids.device
_left_padding = torch.any(attention_mask[:, 0] == 0) _right_padding = torch.any(attention_mask[:, -1] == 0) if _left_padding and _right_padding: raise ValueError(f"both side of attention_mask has zero, invalid. {attention_mask}") left_padding = bool(_left_padding and not _right_padding)
start_mask = input_ids == self.config.ts_token_start_index marker_mask = start_mask | (input_ids == self.config.ts_token_end_index) real = attention_mask.bool()
patch_cnt = patch_cnt.to(device) num_ts_row = start_mask.sum(dim=-1) # series per row n_series = int(num_ts_row.sum()) if n_series != patch_cnt.numel(): raise ValueError( f"{n_series} <ts> markers in the batch but {patch_cnt.numel()} patch counts" )
# Slots each row gains: a series takes patch_cnt slots and already owns its two markers. row_of_series = torch.repeat_interleave(torch.arange(batch_size, device=device), num_ts_row) patches_row = torch.zeros(batch_size, dtype=torch.long, device=device).index_add_( 0, row_of_series, patch_cnt ) num_total_patches = patches_row - 2 * num_ts_row
grow = torch.zeros(batch_size, sequence_length, dtype=torch.long, device=device) grow[start_mask] = patch_cnt - 2 # start_mask.nonzero() is row-major, matching patch_cnt
# Destination of every token within its own row. rank = (real.long().cumsum(dim=-1) - 1).clamp(min=0) # real tokens before this one grow_real = grow * real growth_before = grow_real.cumsum(dim=-1) - grow_real # exclusive prefix sum dest = rank + growth_before
own_len = real.sum(dim=-1) + num_total_patches # expanded length per row max_embed_dim = sequence_length + int(num_total_patches.max()) offset = (max_embed_dim - own_len) if left_padding else torch.zeros_like(own_len) dest = dest + offset[:, None] # the single padding step
# Text tokens; the markers and padding are not placed. final_embedding = torch.zeros( batch_size, max_embed_dim, inputs_embeds.size(-1), dtype=inputs_embeds.dtype, device=inputs_embeds.device, ) text_sel = real & ~marker_mask t_batch, t_pos = text_sel.nonzero(as_tuple=True) final_embedding[t_batch, dest[t_batch, t_pos]] = inputs_embeds[t_batch, t_pos]
final_labels = None if labels is not None: final_labels = torch.full( (batch_size, max_embed_dim), self.config.ignore_index, dtype=labels.dtype, device=labels.device, ) final_labels[t_batch, dest[t_batch, t_pos]] = labels[t_batch, t_pos]
# Patches: one contiguous block per series, starting at its <ts> destination. s_batch, s_pos = start_mask.nonzero(as_tuple=True) block_start = dest[s_batch, s_pos] total_patches = int(patch_cnt.sum()) if time_series_features.shape[0] != total_patches: raise ValueError( f"The input provided to the model are wrong. patch_cnt sums to {total_patches} " f"but {time_series_features.shape[0]} time-series features were given. " "This prevents correct indexing and breaks batch generation." ) series_id = torch.repeat_interleave(torch.arange(n_series, device=device), patch_cnt) within = torch.arange(total_patches, device=device) - torch.repeat_interleave( patch_cnt.cumsum(0) - patch_cnt, patch_cnt ) final_embedding[s_batch[series_id], block_start[series_id] + within] = ( time_series_features.contiguous().to(final_embedding.dtype) )
# Attention mask, positions and the input -> expanded index map. ar = torch.arange(max_embed_dim, device=device)[None, :] final_attention_mask = ( (ar >= offset[:, None]) & (ar < (offset + own_len)[:, None]) ).to(attention_mask.dtype)
position_ids = (final_attention_mask.cumsum(-1) - 1).masked_fill_( final_attention_mask == 0, 1 ) # As in ChatTS, a <ts> marker maps to the end of its patch block. new_token_positions = (dest + grow_real).masked_fill(attention_mask == 0, -1)
return final_embedding, final_attention_mask, position_ids, final_labels, new_token_positions
def _merge_input_ids_with_time_series_features(self, time_series_features, inputs_embeds, input_ids, attention_mask, labels, patch_cnt): """ChatTS's name for :meth:`merge_ununiform_ts`.""" return self.merge_ununiform_ts( time_series_features, inputs_embeds, input_ids, attention_mask, labels, patch_cnt )
@can_return_tuple def forward( self, input_ids: Optional[torch.LongTensor] = None, timeseries: torch.FloatTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs, ) -> Qwen3TSCausalLMOutputWithPast: r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*): Pre-computed hidden-states (key and values in the attention blocks). inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*): Indices depicting the position of the input sequence tokens in the sequence. timeseries (`torch.FloatTensor` of shape `(batch_size, num_patches, patch_size)`, *optional*): Timeseries data to be encoded and merged with text embeddings. Returns: [`Qwen3TSCausalLMOutputWithPast`] or `tuple(torch.FloatTensor)`: The model outputs with potential timeseries-expanded attention mask. """
# if input_ids is not None and timeseries is not None: # # Print the input ts # print("=================================================================") # print("Timeseries shape:", timeseries.shape) # print("=================================================================\n\n") # else: # print("Time series is None!!!!")
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 )
if inputs_embeds is None: inputs_embeds = self.get_input_embeddings()(input_ids)
if timeseries is not None and timeseries.shape[0] > 0: # use_cache = False # print(f"timeseries shape: {timeseries.shape=}, {input_ids.shape=}") ts_features, patch_cnt = self.ts_encoder(timeseries) inputs_embeds = inputs_embeds.to(ts_features.dtype) # if str(input_ids.device) == 'cuda:0': # print(f"-------------------------------------------------------\n[before] {input_ids.shape=}, timeseries={timeseries.shape if timeseries is not None else None}, {attention_mask.sum(-1)=}") inputs_embeds, attention_mask, position_ids, labels, new_token_positions = self.merge_ununiform_ts( ts_features, inputs_embeds, input_ids, attention_mask, labels, patch_cnt ) if cache_position is not None: cache_position = torch.arange( attention_mask.size(-1) - inputs_embeds.size(1), attention_mask.size(-1), device=inputs_embeds.device )
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) # if str(input_ids.device) == 'cuda:0': # print(f"[after] {inputs_embeds.shape=}, {attention_mask.sum(-1)=}, {position_ids.max(-1)=}, {cache_position.max().item()=}") outputs: BaseModelOutputWithPast = self.model( attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, cache_position=cache_position, **kwargs, )
hidden_states = outputs.last_hidden_state # Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :])
loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs) # print(f"{logits.shape=}, {hidden_states.shape=}, {slice_indices=}, {logits_to_keep=}, labels={(labels != self.config.ignore_index).sum() if labels is not None else None}, {loss=}, {torch.sum(torch.isnan(logits))=}, {torch.sum(torch.isinf(logits))=}, {torch.sum(torch.isnan(hidden_states))=}, {torch.sum(torch.isinf(hidden_states))=}")
return Qwen3TSCausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, last_hidden_state=hidden_states, hidden_states=outputs.hidden_states, attentions=outputs.attentions, attention_mask=attention_mask, labels=labels, new_token_positions=new_token_positions if timeseries is not None and timeseries.shape[0] > 0 else None, )
__all__ = [ "Qwen3TSForCausalLM"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224# coding=utf-8# Copyright 2024 Tsinghua University and ByteDance.## Licensed under the MIT License (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://opensource.org/license/mit## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import numpy as npfrom typing import List, Union, Tuple, Optionalimport torch
from transformers.feature_extraction_utils import BatchFeaturefrom transformers.processing_utils import ProcessorMixinfrom transformers.tokenization_utils_base import PaddingStrategy
def sp_encoding(timeseries: np.ndarray, eots_token: bool = True) -> Tuple[np.ndarray, str, dict]: """ Encodes a time series with scalar normalization.
Args: timeseries (np.ndarray): The raw time series data (1D or 2D).
Returns: result_timeseries (np.ndarray): The encoded time series, shape [seq_len, 1]. prompt (str): The placeholder string with offset and scaling info. metadata (dict): Metadata containing the offset and scaling factor. """ timeseries = np.array(timeseries) mean = np.mean(timeseries) scaled_timeseries = timeseries - mean scale_factor = 1.0 if np.any(np.abs(scaled_timeseries) >= 3.0): scale_factor = np.max(np.abs(scaled_timeseries)) / 3.0 scaled_timeseries /= scale_factor
prompt = f"[offset={-mean:.4f}|scaling={scale_factor:.4f}|length={len(timeseries)}|max={max(timeseries):.4f}|min={min(timeseries):.4f}|left={timeseries[0]:.4f}|right={timeseries[-1]:.4f}]<ts>" if eots_token: prompt += '<ts/>'
result_timeseries = np.stack([scaled_timeseries, np.ones_like(scaled_timeseries)], axis=-1).reshape(-1, 1)
return result_timeseries, prompt, {"offset": float(-mean), "scale_factor": float(scale_factor)}
class Qwen3TSProcessor(ProcessorMixin): """ A processor for ChatTS that integrates text prompt processing and time series encoding. """
attributes = ["tokenizer"] feature_extractor_class = None # You can add a feature extractor if needed tokenizer_class = "AutoTokenizer"
def __init__(self, tokenizer=None, chat_template=None, **kwargs): """ Args: tokenizer: An optional tokenizer to process text prompts. """ if chat_template is None and tokenizer is not None and tokenizer.chat_template is not None: chat_template = tokenizer.chat_template self.chat_template = chat_template
super().__init__(tokenizer=tokenizer, chat_template=chat_template, **kwargs)
def __call__( self, text: Union[str, List[str]], timeseries: Optional[List[List[np.ndarray]]] = None, padding: Union[bool, str, PaddingStrategy] = False, padding_side: str = 'left', vllm_flag: bool = False, tokenize: bool = True, **kwargs, ) -> BatchFeature: """ Encodes a prompt and its associated time series.
Args: prompt (List[str]): The input prompt containing <ts><ts/> placeholders. timeseries (List[np.ndarray]): A list of time series matched to placeholders in the prompt. padding (bool or str or PaddingStrategy, optional): Passed to the tokenizer for text padding. return_tensors (str, optional): "pt" to return PyTorch tensors; None to return NumPy arrays. **kwargs: Additional tokenizer parameters.
Returns: BatchFeature: Contains processed prompt, encoded time series, and tokenizer outputs. """ if type(text) == str: text = [text] if timeseries is None: timeseries = []
reconstructed_prompts = [] concatenated_ts = None ts_tokens = []
if vllm_flag: # All prompt modifications have to be done inside of the vLLM # to work correctly with its caching mechanism. reconstructed_prompts = text # Process timeseries data encoded_ts_arrays = [] for ts in timeseries: # Get the normalized data and prompt text encoded_ts, ts_prompt, _ = sp_encoding(ts, eots_token=False) # Tokenize the ts_prompt and add to the tokens list if self.tokenizer is not None: tokens = self.tokenizer.encode(ts_prompt, add_special_tokens=False) ts_tokens.append(tokens) encoded_ts_arrays.append(encoded_ts[None, ...]) else: encoded_ts_arrays = [] total_ts_cnt = 0 for idx, prompt in enumerate(text): # Split prompt by <ts><ts/> placeholders last_ts_cnt = total_ts_cnt prompt_segments = prompt.split("<ts><ts/>") total_ts_cnt = total_ts_cnt + len(prompt_segments) - 1
# Encode each time series and rebuild the prompt reconstructed_prompt = prompt_segments[0]
for i, ts in enumerate(timeseries[last_ts_cnt:total_ts_cnt]): encoded_ts, ts_prompt, _ = sp_encoding(ts, eots_token=not vllm_flag) reconstructed_prompt += ts_prompt + prompt_segments[i + 1] # Ensure time series shape [1, seq_len, feature_dim] for batch concatenation encoded_ts_arrays.append(encoded_ts[None, ...])
reconstructed_prompts.append(reconstructed_prompt)
if len(timeseries) != len(encoded_ts_arrays): raise ValueError( f"Mismatch between <ts><ts/> placeholders ({total_ts_cnt}) " f"and time series ({len(encoded_ts_arrays)})." )
if len(encoded_ts_arrays) > 0: # Pad time series to the same length max_length = max(ts.shape[1] for ts in encoded_ts_arrays) padded_ts_arrays = [ np.pad(ts, ((0, 0), (0, max_length - ts.shape[1]), (0, 0)), mode="constant", constant_values=0.0) for ts in encoded_ts_arrays ] concatenated_ts = np.concatenate(padded_ts_arrays, axis=0) # Shape: [batch_size, max_length, feature_dim] # Convert to torch concatenated_ts = torch.from_numpy(concatenated_ts).half()
# Tokenize the processed prompt tokenizer_outputs = {} if tokenize and self.tokenizer is not None: tokenizer_outputs = self.tokenizer(reconstructed_prompts, padding=padding, padding_side=padding_side, **kwargs) else: tokenizer_outputs = {"text": reconstructed_prompts}
# Create the final output outputs = tokenizer_outputs if vllm_flag: outputs["timeseries"] = zip(ts_tokens, encoded_ts_arrays) elif concatenated_ts is not None: outputs["timeseries"] = concatenated_ts
return BatchFeature(data=outputs)
def encode_timeseries( self, timeseries: Optional[List[List[np.ndarray]]] = None, ) -> np.ndarray: if timeseries is None: timeseries = []
concatenated_ts = None encoded_ts_arrays = []
for i, ts in enumerate(timeseries): encoded_ts, _, _ = sp_encoding(ts) # Ensure time series shape [1, seq_len, feature_dim] for batch concatenation encoded_ts_arrays.append(encoded_ts[None, ...])
if len(encoded_ts_arrays) > 0: # Pad time series to the same length max_length = max(ts.shape[1] for ts in encoded_ts_arrays) padded_ts_arrays = [ np.pad(ts, ((0, 0), (0, max_length - ts.shape[1]), (0, 0)), mode="constant", constant_values=0.0) for ts in encoded_ts_arrays ] concatenated_ts = np.concatenate(padded_ts_arrays, axis=0) # Shape: [batch_size, max_length, feature_dim] # Convert to torch concatenated_ts = torch.from_numpy(concatenated_ts).half()
return concatenated_ts
@property def model_input_names(self): """ Define the input names expected by the model. """ tokenizer_input_names = [] if self.tokenizer and hasattr(self.tokenizer, "model_input_names"): tokenizer_input_names = self.tokenizer.model_input_names return list(dict.fromkeys(["processed_prompt", "time_series"] + tokenizer_input_names))
def batch_decode(self, *args, **kwargs): """ This method forwards all its arguments to Qwen3TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please refer to the docstring of this method for more information. """ return self.tokenizer.batch_decode(*args, **kwargs)
def decode(self, *args, **kwargs): """ This method forwards all its arguments to Qwen3TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to the docstring of this method for more information. """ return self.tokenizer.decode(*args, **kwargs)123456{ "auto_map": { "AutoProcessor": "processing_qwen3_ts.Qwen3TSProcessor" }, "processor_class": "Qwen3TSProcessor"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425{ "metadata": { "total_parameters": 347136, "total_size": 16557938720 }, "weight_map": { "codi_mae_applier.mask_token": "pytorch_model-00004-of-00004.bin", "codi_projection.1.bias": "pytorch_model-00004-of-00004.bin", "codi_projection.1.weight": "pytorch_model-00004-of-00004.bin", "codi_projection.3.bias": "pytorch_model-00004-of-00004.bin", "codi_projection.3.weight": "pytorch_model-00004-of-00004.bin", "codi_projection.ln.bias": "pytorch_model-00004-of-00004.bin", "codi_projection.ln.weight": "pytorch_model-00004-of-00004.bin", "lm_head.weight": "pytorch_model-00004-of-00004.bin", "model.embed_tokens.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.10.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.2.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.20.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.22.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.22.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.22.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.22.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.22.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.22.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.22.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.22.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.22.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.22.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.22.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.23.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.3.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.30.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.35.input_layernorm.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.mlp.down_proj.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.mlp.gate_proj.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.mlp.up_proj.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.post_attention_layernorm.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.self_attn.k_norm.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.35.self_attn.o_proj.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.self_attn.q_norm.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.35.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.4.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.9.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.9.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.9.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.9.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.9.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.9.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.9.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.9.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.9.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.9.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.9.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.norm.weight": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.0.bias": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.0.weight": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.2.bias": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.2.weight": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.4.bias": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.4.weight": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.6.bias": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.6.weight": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.8.bias": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.8.weight": "pytorch_model-00004-of-00004.bin", "ts_encoder.position_embedding.weight": "pytorch_model-00004-of-00004.bin" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265{ "add_bos_token": false, "add_prefix_space": false, "added_tokens_decoder": { "151643": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151644": { "content": "<|im_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151645": { "content": "<|im_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151646": { "content": "<|object_ref_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151647": { "content": "<|object_ref_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151648": { "content": "<|box_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151649": { "content": "<|box_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151650": { "content": "<|quad_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151651": { "content": "<|quad_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151652": { "content": "<|vision_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151653": { "content": "<|vision_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151654": { "content": "<|vision_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151655": { "content": "<|image_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151656": { "content": "<|video_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151657": { "content": "<tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151658": { "content": "</tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151659": { "content": "<|fim_prefix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151660": { "content": "<|fim_middle|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151661": { "content": "<|fim_suffix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151662": { "content": "<|fim_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151663": { "content": "<|repo_name|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151664": { "content": "<|file_sep|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151665": { "content": "<tool_response>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151666": { "content": "</tool_response>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151667": { "content": "<think>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151668": { "content": "</think>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151669": { "content": "<ts>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151670": { "content": "<ts/>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151671": { "content": "<|bot|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151672": { "content": "<|eot|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true } }, "additional_special_tokens": [ "<ts>", "<ts/>" ], "auto_map": { "AutoProcessor": "processing_qwen3_ts.Qwen3TSProcessor" }, "bos_token": null, "clean_up_tokenization_spaces": false, "eos_token": "<|im_end|>", "errors": "replace", "extra_special_tokens": {}, "model_max_length": 131072, "pad_token": "<|endoftext|>", "padding_side": "right", "processor_class": "Qwen3TSProcessor", "split_special_tokens": false, "tokenizer_class": "Qwen2Tokenizer", "unk_token": null}1234567891011121314151617181920212223242526272829303132{ "</think>": 151668, "</tool_call>": 151658, "</tool_response>": 151666, "<think>": 151667, "<tool_call>": 151657, "<tool_response>": 151665, "<ts/>": 151670, "<ts>": 151669, "<|bot|>": 151671, "<|box_end|>": 151649, "<|box_start|>": 151648, "<|endoftext|>": 151643, "<|eot|>": 151672, "<|file_sep|>": 151664, "<|fim_middle|>": 151660, "<|fim_pad|>": 151662, "<|fim_prefix|>": 151659, "<|fim_suffix|>": 151661, "<|im_end|>": 151645, "<|im_start|>": 151644, "<|image_pad|>": 151655, "<|object_ref_end|>": 151647, "<|object_ref_start|>": 151646, "<|quad_end|>": 151651, "<|quad_start|>": 151650, "<|repo_name|>": 151663, "<|video_pad|>": 151656, "<|vision_end|>": 151653, "<|vision_pad|>": 151654, "<|vision_start|>": 151652}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889{%- if tools %} {{- '<|im_start|>system\n' }} {%- if messages[0].role == 'system' %} {{- messages[0].content + '\n\n' }} {%- 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' }} {%- 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 message.content is string 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.content is string %} {%- set content = message.content %} {%- else %} {%- set content = '' %} {%- endif %} {%- if (message.role == "user") or (message.role == "system" and not loop.first) %} {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} {%- elif message.role == "assistant" %} {%- set reasoning_content = '' %} {%- if message.reasoning_content is string %} {%- set reasoning_content = message.reasoning_content %} {%- else %} {%- if '</think>' in content %} {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %} {%- set content = content.split('</think>')[-1].lstrip('\n') %} {%- endif %} {%- endif %} {%- if loop.index0 > ns.last_query_index %} {%- if loop.last or (not loop.last and reasoning_content) %} {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }} {%- else %} {{- '<|im_start|>' + message.role + '\n' + content }} {%- endif %} {%- else %} {{- '<|im_start|>' + message.role + '\n' + content }} {%- endif %} {%- 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' }} {{- 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' }} {%- if enable_thinking is defined and enable_thinking is false %} {{- '<think>\n\n</think>\n\n' }} {%- endif %}{%- endif %}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990{ "architectures": [ "Qwen3TSForCausalLM" ], "attention_bias": false, "attention_dropout": 0.0, "auto_map": { "AutoConfig": "configuration_qwen3_ts.Qwen3TSConfig", "AutoModel": "modeling_qwen3_ts.Qwen3TSForCausalLM", "AutoModelForCausalLM": "modeling_qwen3_ts.Qwen3TSForCausalLM", "AutoProcessor": "processing_qwen3_ts.Qwen3TSProcessor" }, "bos_token_id": 151643, "eos_token_id": 151645, "head_dim": 128, "hidden_act": "silu", "hidden_size": 4096, "ignore_index": -100, "initializer_range": 0.02, "intermediate_size": 12288, "layer_types": [ "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention" ], "max_position_embeddings": 40960, "max_window_layers": 36, "model_type": "qwen3ts", "num_attention_heads": 32, "num_hidden_layers": 36, "num_key_value_heads": 8, "pad_token_id": 151643, "rms_norm_eps": 1e-06, "rope_scaling": null, "rope_theta": 1000000, "sliding_window": null, "tie_word_embeddings": false, "torch_dtype": "bfloat16", "transformers_version": "4.55.4", "ts": { "embedding_dim": 16, "hidden_size": 4096, "max_length": 32768, "max_sequence_length": 8192, "num_features": 2, "num_layers": 5, "patch_size": 8, "use_layer_norm": false, "use_position_embedding": true, "use_position_idx": false }, "ts_token_end_index": 151670, "ts_token_start_index": 151669, "use_cache": false, "use_sliding_window": false, "vocab_size": 151936}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225# coding=utf-8# Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Qwen3 model configuration"""
from transformers.configuration_utils import PretrainedConfigfrom transformers.modeling_rope_utils import rope_config_validationfrom transformers.utils import logging
logger = logging.get_logger(__name__)
class Qwen3TSConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`Qwen3Model`]. It is used to instantiate a Qwen3 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of Qwen3-8B [Qwen/Qwen3-8B](https://huggingface.co/Qwen/Qwen3-8B).
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.
Args: vocab_size (`int`, *optional*, defaults to 151936): Vocabulary size of the Qwen3 model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`Qwen3Model`] hidden_size (`int`, *optional*, defaults to 4096): Dimension of the hidden representations. intermediate_size (`int`, *optional*, defaults to 22016): Dimension of the MLP representations. num_hidden_layers (`int`, *optional*, defaults to 32): Number of hidden layers in the Transformer encoder. num_attention_heads (`int`, *optional*, defaults to 32): Number of attention heads for each attention layer in the Transformer encoder. num_key_value_heads (`int`, *optional*, defaults to 32): This is the number of key_value heads that should be used to implement Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details, check out [this paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`. head_dim (`int`, *optional*, defaults to 128): The attention head dimension. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`): The non-linear activation function (function or string) in the decoder. max_position_embeddings (`int`, *optional*, defaults to 32768): The maximum sequence length that this model might ever be used with. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. rms_norm_eps (`float`, *optional*, defaults to 1e-06): The epsilon used by the rms normalization layers. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True`. tie_word_embeddings (`bool`, *optional*, defaults to `False`): Whether the model's input and output word embeddings should be tied. rope_theta (`float`, *optional*, defaults to 10000.0): The base period of the RoPE embeddings. rope_scaling (`Dict`, *optional*): Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value accordingly. Expected contents: `rope_type` (`str`): The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope', 'llama3'], with 'default' being the original RoPE implementation. `factor` (`float`, *optional*): Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In most scaling types, a `factor` of x will enable the model to handle sequences of length x * original maximum pre-trained length. `original_max_position_embeddings` (`int`, *optional*): Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during pretraining. `attention_factor` (`float`, *optional*): Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention computation. If unspecified, it defaults to value recommended by the implementation, using the `factor` field to infer the suggested value. `beta_fast` (`float`, *optional*): Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear ramp function. If unspecified, it defaults to 32. `beta_slow` (`float`, *optional*): Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear ramp function. If unspecified, it defaults to 1. `short_factor` (`list[float]`, *optional*): Only used with 'longrope'. The scaling factor to be applied to short contexts (< `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 `long_factor` (`list[float]`, *optional*): Only used with 'longrope'. The scaling factor to be applied to long contexts (< `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 `low_freq_factor` (`float`, *optional*): Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE `high_freq_factor` (`float`, *optional*): Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`): Whether to use a bias in the query, key, value and output projection layers during self-attention. use_sliding_window (`bool`, *optional*, defaults to `False`): Whether to use sliding window attention. sliding_window (`int`, *optional*, defaults to 4096): Sliding window attention (SWA) window size. If not specified, will default to `4096`. max_window_layers (`int`, *optional*, defaults to 28): The number of layers using full attention. The first `max_window_layers` layers will use full attention, while any additional layer afterwards will use SWA (Sliding Window Attention). layer_types (`list`, *optional*): Attention pattern for each layer. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities.
```python >>> from transformers import Qwen3Model, Qwen3Config
>>> # Initializing a Qwen3 style configuration >>> configuration = Qwen3Config()
>>> # Initializing a model from the Qwen3-8B style configuration >>> model = Qwen3Model(configuration)
>>> # Accessing the model configuration >>> configuration = model.config ```"""
model_type = "qwen3ts" keys_to_ignore_at_inference = ["past_key_values"]
# Default tensor parallel plan for base model `Qwen3` base_model_tp_plan = { "layers.*.self_attn.q_proj": "colwise", "layers.*.self_attn.k_proj": "colwise", "layers.*.self_attn.v_proj": "colwise", "layers.*.self_attn.o_proj": "rowwise", "layers.*.mlp.gate_proj": "colwise", "layers.*.mlp.up_proj": "colwise", "layers.*.mlp.down_proj": "rowwise", } base_model_pp_plan = { "embed_tokens": (["input_ids"], ["inputs_embeds"]), "layers": (["hidden_states", "attention_mask"], ["hidden_states"]), "norm": (["hidden_states"], ["hidden_states"]), }
def __init__( self, vocab_size=151936, hidden_size=4096, intermediate_size=22016, num_hidden_layers=32, num_attention_heads=32, num_key_value_heads=32, head_dim=128, hidden_act="silu", max_position_embeddings=32768, initializer_range=0.02, rms_norm_eps=1e-6, use_cache=True, tie_word_embeddings=False, rope_theta=10000.0, rope_scaling=None, attention_bias=False, use_sliding_window=False, sliding_window=4096, max_window_layers=28, layer_types=None, attention_dropout=0.0, **kwargs, ): self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.use_sliding_window = use_sliding_window self.sliding_window = sliding_window if self.use_sliding_window else None self.max_window_layers = max_window_layers
# for backward compatibility if num_key_value_heads is None: num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads self.head_dim = head_dim self.hidden_act = hidden_act self.initializer_range = initializer_range self.rms_norm_eps = rms_norm_eps self.use_cache = use_cache self.rope_theta = rope_theta self.rope_scaling = rope_scaling self.attention_bias = attention_bias self.attention_dropout = attention_dropout # Validate the correctness of rotary position embeddings parameters # BC: if there is a 'type' field, move it to 'rope_type'. if self.rope_scaling is not None and "type" in self.rope_scaling: self.rope_scaling["rope_type"] = self.rope_scaling["type"] rope_config_validation(self)
self.layer_types = layer_types if self.layer_types is None: self.layer_types = [ "sliding_attention" if self.sliding_window is not None and i >= self.max_window_layers else "full_attention" for i in range(self.num_hidden_layers) ]
super().__init__( tie_word_embeddings=tie_word_embeddings, **kwargs, )
__all__ = ["Qwen3TSConfig"]12345678910111213{ "bos_token_id": 151643, "do_sample": true, "eos_token_id": [ 151645, 151643 ], "pad_token_id": 151643, "temperature": 0.6, "top_k": 20, "top_p": 0.95, "transformers_version": "4.55.4"}123456789101112{ "stage": "lapras", "template": "chatts", "ts_patch_size": 8, "answer_anchor": "Answer:", "use_cot": null, "num_latent": 6, "projection": { "projection_dim": 2048 }, "remove_eos": true}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601# Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
from typing import Callable, Optional, Union
import torchfrom torch import nnfrom dataclasses import dataclass
from transformers.cache_utils import Cachefrom transformers.generation import GenerationMixinfrom transformers.modeling_flash_attention_utils import FlashAttentionKwargsfrom transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast)from transformers.models.qwen3.modeling_qwen3 import Qwen3PreTrainedModel, Qwen3Modelfrom transformers.modeling_utils import PreTrainedModelfrom transformers.processing_utils import Unpackfrom transformers.utils import auto_docstring, can_return_tuple, logging, ModelOutputfrom .configuration_qwen3_ts import Qwen3TSConfigfrom typing import Any, Dict
logger = logging.get_logger(__name__)
########################MLP TS Embedding#####################class TimeSeriesEmbedding(nn.Module): def __init__(self, config): super(TimeSeriesEmbedding, self).__init__() self.patch_size = config['patch_size'] self.num_layers = config['num_layers'] self.hidden_size = config['hidden_size'] self.num_features = config['num_features'] self.max_sequence_length = config['max_sequence_length'] # Maximum time series length self.use_position_embedding = config.get('use_position_embedding', False) self.use_position_idx = config.get('use_position_idx', False) self.use_layer_norm = config.get('use_layer_norm', False) self.embedding_dim = config.get('embedding_dim', 16) # Embedding dimension if self.use_position_embedding: # Extended vocabulary: [0, max_sequence_length) for real positions, max_sequence_length for padding self.position_embedding = nn.Embedding(self.max_sequence_length + 1, self.embedding_dim) self.padding_idx = self.max_sequence_length # Special index for padding input_size = 1 * self.patch_size + self.embedding_dim * self.patch_size elif self.use_position_idx: input_size = 2 * self.patch_size else: input_size = 1 * self.patch_size # Build MLP layers layers = [] for _ in range(self.num_layers - 1): layers.append(nn.Linear(input_size, self.hidden_size)) layers.append(nn.GELU()) input_size = self.hidden_size
layers.append(nn.Linear(input_size, self.hidden_size)) if self.use_layer_norm: layers.append(nn.LayerNorm(self.hidden_size))
self.mlp = nn.Sequential(*layers)
def forward(self, x: torch.Tensor): batch_size = x.size(0) x = x.reshape(batch_size, -1, self.num_features)
# Extract mask and calculate valid lengths mask = x[:, :, -1].long() valid_lengths = mask.sum(dim=1).long() patch_cnt = (valid_lengths + self.patch_size - 1) // self.patch_size
patches_list = [] # Collect position indices for batch embedding lookup all_position_indices = [] patch_info_list = [] # Store metadata for each patch group for i in range(batch_size): vl = valid_lengths[i].item() pc = patch_cnt[i].item() if pc == 0: continue # Extract time series data (excluding mask) xi = x[i, :vl, :1] # Time-series data total_padded_length = pc * self.patch_size padding_length = total_padded_length - vl # Create position indices: real positions for actual data, special index for padding position_indices = torch.arange(vl, device=x.device) if padding_length > 0: # Pad with last value last_value = xi[-1:, :] padding = last_value.repeat(padding_length, 1) xi = torch.cat([xi, padding], dim=0) # Use special padding index for padding positions padding_positions = torch.full((padding_length,), self.padding_idx, device=x.device) position_indices = torch.cat([position_indices, padding_positions], dim=0)
# Reshape to patches xi = xi.reshape(pc, self.patch_size) # (num_patches, patch_size) position_indices = position_indices.reshape(pc, self.patch_size) # (num_patches, patch_size)
if self.use_position_embedding: # Collect position indices instead of calling embedding immediately all_position_indices.append(position_indices) patch_info_list.append({ 'xi': xi, 'pc': pc, 'sample_idx': i }) elif self.use_position_idx: # Normalize position indices pos_indices = torch.arange(vl, device=x.device).unsqueeze(1) pos_indices = pos_indices / max(1, valid_lengths.max().item() - 1) if padding_length > 0: # Use -1 for padding positions padding_indices = torch.full((padding_length, 1), -1, device=x.device) pos_indices = torch.cat([pos_indices, padding_indices], dim=0) # Combine time series data with position indices xi_combined = torch.cat([xi.reshape(-1, 1), pos_indices], dim=1) patch_input = xi_combined.reshape(pc, self.patch_size * 2) patches_list.append(patch_input) else: # No position embedding, use raw patches patch_input = xi patches_list.append(patch_input)
# Batch process position embeddings if needed if self.use_position_embedding and all_position_indices: # Concatenate all position indices for batch embedding lookup batch_position_indices = torch.cat(all_position_indices, dim=0) # print(f"{x.shape=}, {x.device=}, {len(all_position_indices)=}, {batch_position_indices=}") batch_pos_emb = self.position_embedding(batch_position_indices) # Single embedding call # Split embeddings back and create patch inputs emb_start_idx = 0 for patch_info in patch_info_list: xi = patch_info['xi'] pc = patch_info['pc'] # Extract corresponding embeddings pos_emb = batch_pos_emb[emb_start_idx:emb_start_idx + pc] emb_start_idx += pc # Flatten and concatenate xi = xi.unsqueeze(-1) # (num_patches, patch_size, 1) patch_input = torch.cat([ xi.flatten(1), # (num_patches, patch_size) pos_emb.flatten(1) # (num_patches, patch_size * embedding_dim) ], dim=1) patches_list.append(patch_input)
# Process all patches through MLP if patches_list: x_patches = torch.cat(patches_list, dim=0) x = self.mlp(x_patches) else: # Handle empty case x = torch.empty(0, self.hidden_size, device=x.device)
return x, patch_cnt
@dataclassclass Qwen3TSCausalLMOutputWithPast(CausalLMOutputWithPast): """ Output type of Qwen3TSForCausalLM that includes additional fields for timeseries processing. Args: loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Language modeling loss (for next-token prediction). logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed): Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*): The attention mask used in the forward pass, potentially expanded to accommodate timeseries patches. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. new_token_positions (`torch.LongTensor` of shape `(batch_size, num_new_tokens)`, *optional*): Positions where new tokens (not from timeseries) are located in the expanded sequence. """ last_hidden_state: Optional[torch.FloatTensor] = None attention_mask: Optional[torch.FloatTensor] = None labels: Optional[torch.LongTensor] = None new_token_positions: Optional[torch.LongTensor] = None
class Qwen3TSGenerationMixin(GenerationMixin): """ Generation mixin for Qwen3 models with timeseries support. This mixin handles the special case where timeseries embeddings expand the sequence length during the first forward pass, requiring special attention mask management. """ def prepare_inputs_for_generation( self, input_ids: torch.LongTensor, past_key_values: Optional[Cache] = None, attention_mask: Optional[torch.LongTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, cache_position: Optional[torch.LongTensor] = None, timeseries: Optional[torch.FloatTensor] = None, **kwargs, ) -> Dict[str, Any]: """ Prepare inputs for generation with timeseries support. Timeseries are only processed during the first forward pass. In subsequent generation steps, they are already embedded in the past_key_values. """ # Check if we have timeseries data has_ts = timeseries is not None and len(timeseries) > 0 # Handle timeseries for generation with past_key_values if has_ts and past_key_values is not None: # Get the number of tokens already processed if isinstance(past_key_values, Cache): if hasattr(past_key_values, 'seen_tokens'): past_length = past_key_values.seen_tokens else: past_length = past_key_values.get_seq_length() else: past_length = past_key_values[0][0].shape[2] if past_key_values[0] is not None else 0 # If we have processed tokens, timeseries have already been embedded if past_length > 0: # Only keep the last token for next token prediction input_ids = input_ids[:, -1:] # Clear timeseries as they've been processed timeseries = None has_ts = False # Call parent's prepare_inputs_for_generation to handle all standard logic # print(f"[debug] {input_ids.shape=}, {attention_mask.shape=}, {cache_position.max()=}, {past_length=}, {has_ts=}") model_inputs = super().prepare_inputs_for_generation( input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, inputs_embeds=inputs_embeds, cache_position=cache_position, **kwargs ) # Add timeseries to model inputs model_inputs["timeseries"] = timeseries return model_inputs def _update_model_kwargs_for_generation( self, outputs: ModelOutput, model_kwargs: Dict[str, Any], is_encoder_decoder: bool = False, num_new_tokens: int = 1, ) -> Dict[str, Any]: """ Update model keyword arguments for generation, handling attention mask from outputs. This is necessary because timeseries processing can expand the sequence length, and we need to use the expanded attention_mask from the model outputs. """ # Handle special case: use attention_mask from outputs if available # This is crucial for timeseries models where the sequence length is expanded if hasattr(outputs, "attention_mask") and outputs.attention_mask is not None: model_kwargs["attention_mask"] = outputs.attention_mask # Call parent's implementation for standard updates model_kwargs = super()._update_model_kwargs_for_generation( outputs=outputs, model_kwargs=model_kwargs, is_encoder_decoder=is_encoder_decoder, num_new_tokens=num_new_tokens, ) return model_kwargs def generate( self, inputs: Optional[torch.Tensor] = None, timeseries: Optional[torch.FloatTensor] = None, generation_config=None, **kwargs, ): """ Generate sequences with timeseries support. Args: inputs: Input token ids timeseries: Optional timeseries data to be processed in the first forward pass generation_config: Generation configuration **kwargs: Additional keyword arguments for generation """ # Add timeseries to kwargs if provided if timeseries is not None: kwargs["timeseries"] = timeseries # Call parent's generate method return super().generate( inputs=inputs, generation_config=generation_config, **kwargs, ) def _validate_model_kwargs(self, model_kwargs: Dict[str, Any]) -> None: """ Validate model kwargs, allowing timeseries as a valid argument. """ # Remove timeseries from model_kwargs temporarily for validation timeseries = model_kwargs.pop("timeseries", None) # Call parent's validation super()._validate_model_kwargs(model_kwargs) # Restore timeseries if timeseries is not None: model_kwargs["timeseries"] = timeseries
class Qwen3TSPreTrainedModel(Qwen3PreTrainedModel): config_class = Qwen3TSConfig
@auto_docstringclass Qwen3TSForCausalLM(Qwen3TSPreTrainedModel, Qwen3TSGenerationMixin): _tied_weights_keys = ["lm_head.weight"] _tp_plan = {"lm_head": "colwise_rep"} _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config): super().__init__(config) self.model = Qwen3Model(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# TS embedding self.ts_encoder = TimeSeriesEmbedding(config.ts)
# Initialize weights and apply final processing 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 merge_ununiform_ts(self, time_series_features, inputs_embeds, input_ids, attention_mask, labels, patch_cnt): """Merge the TS patch embeddings into the token sequence; rows may hold different patch counts.""" batch_size, sequence_length = input_ids.shape device = input_ids.device
_left_padding = torch.any(attention_mask[:, 0] == 0) _right_padding = torch.any(attention_mask[:, -1] == 0) if _left_padding and _right_padding: raise ValueError(f"both side of attention_mask has zero, invalid. {attention_mask}") left_padding = bool(_left_padding and not _right_padding)
start_mask = input_ids == self.config.ts_token_start_index marker_mask = start_mask | (input_ids == self.config.ts_token_end_index) real = attention_mask.bool()
patch_cnt = patch_cnt.to(device) num_ts_row = start_mask.sum(dim=-1) # series per row n_series = int(num_ts_row.sum()) if n_series != patch_cnt.numel(): raise ValueError( f"{n_series} <ts> markers in the batch but {patch_cnt.numel()} patch counts" )
# Slots each row gains: a series takes patch_cnt slots and already owns its two markers. row_of_series = torch.repeat_interleave(torch.arange(batch_size, device=device), num_ts_row) patches_row = torch.zeros(batch_size, dtype=torch.long, device=device).index_add_( 0, row_of_series, patch_cnt ) num_total_patches = patches_row - 2 * num_ts_row
grow = torch.zeros(batch_size, sequence_length, dtype=torch.long, device=device) grow[start_mask] = patch_cnt - 2 # start_mask.nonzero() is row-major, matching patch_cnt
# Destination of every token within its own row. rank = (real.long().cumsum(dim=-1) - 1).clamp(min=0) # real tokens before this one grow_real = grow * real growth_before = grow_real.cumsum(dim=-1) - grow_real # exclusive prefix sum dest = rank + growth_before
own_len = real.sum(dim=-1) + num_total_patches # expanded length per row max_embed_dim = sequence_length + int(num_total_patches.max()) offset = (max_embed_dim - own_len) if left_padding else torch.zeros_like(own_len) dest = dest + offset[:, None] # the single padding step
# Text tokens; the markers and padding are not placed. final_embedding = torch.zeros( batch_size, max_embed_dim, inputs_embeds.size(-1), dtype=inputs_embeds.dtype, device=inputs_embeds.device, ) text_sel = real & ~marker_mask t_batch, t_pos = text_sel.nonzero(as_tuple=True) final_embedding[t_batch, dest[t_batch, t_pos]] = inputs_embeds[t_batch, t_pos]
final_labels = None if labels is not None: final_labels = torch.full( (batch_size, max_embed_dim), self.config.ignore_index, dtype=labels.dtype, device=labels.device, ) final_labels[t_batch, dest[t_batch, t_pos]] = labels[t_batch, t_pos]
# Patches: one contiguous block per series, starting at its <ts> destination. s_batch, s_pos = start_mask.nonzero(as_tuple=True) block_start = dest[s_batch, s_pos] total_patches = int(patch_cnt.sum()) if time_series_features.shape[0] != total_patches: raise ValueError( f"The input provided to the model are wrong. patch_cnt sums to {total_patches} " f"but {time_series_features.shape[0]} time-series features were given. " "This prevents correct indexing and breaks batch generation." ) series_id = torch.repeat_interleave(torch.arange(n_series, device=device), patch_cnt) within = torch.arange(total_patches, device=device) - torch.repeat_interleave( patch_cnt.cumsum(0) - patch_cnt, patch_cnt ) final_embedding[s_batch[series_id], block_start[series_id] + within] = ( time_series_features.contiguous().to(final_embedding.dtype) )
# Attention mask, positions and the input -> expanded index map. ar = torch.arange(max_embed_dim, device=device)[None, :] final_attention_mask = ( (ar >= offset[:, None]) & (ar < (offset + own_len)[:, None]) ).to(attention_mask.dtype)
position_ids = (final_attention_mask.cumsum(-1) - 1).masked_fill_( final_attention_mask == 0, 1 ) # As in ChatTS, a <ts> marker maps to the end of its patch block. new_token_positions = (dest + grow_real).masked_fill(attention_mask == 0, -1)
return final_embedding, final_attention_mask, position_ids, final_labels, new_token_positions
def _merge_input_ids_with_time_series_features(self, time_series_features, inputs_embeds, input_ids, attention_mask, labels, patch_cnt): """ChatTS's name for :meth:`merge_ununiform_ts`.""" return self.merge_ununiform_ts( time_series_features, inputs_embeds, input_ids, attention_mask, labels, patch_cnt )
@can_return_tuple def forward( self, input_ids: Optional[torch.LongTensor] = None, timeseries: torch.FloatTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs, ) -> Qwen3TSCausalLMOutputWithPast: r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*): Pre-computed hidden-states (key and values in the attention blocks). inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*): Indices depicting the position of the input sequence tokens in the sequence. timeseries (`torch.FloatTensor` of shape `(batch_size, num_patches, patch_size)`, *optional*): Timeseries data to be encoded and merged with text embeddings. Returns: [`Qwen3TSCausalLMOutputWithPast`] or `tuple(torch.FloatTensor)`: The model outputs with potential timeseries-expanded attention mask. """
# if input_ids is not None and timeseries is not None: # # Print the input ts # print("=================================================================") # print("Timeseries shape:", timeseries.shape) # print("=================================================================\n\n") # else: # print("Time series is None!!!!")
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 )
if inputs_embeds is None: inputs_embeds = self.get_input_embeddings()(input_ids)
if timeseries is not None and timeseries.shape[0] > 0: # use_cache = False # print(f"timeseries shape: {timeseries.shape=}, {input_ids.shape=}") ts_features, patch_cnt = self.ts_encoder(timeseries) inputs_embeds = inputs_embeds.to(ts_features.dtype) # if str(input_ids.device) == 'cuda:0': # print(f"-------------------------------------------------------\n[before] {input_ids.shape=}, timeseries={timeseries.shape if timeseries is not None else None}, {attention_mask.sum(-1)=}") inputs_embeds, attention_mask, position_ids, labels, new_token_positions = self.merge_ununiform_ts( ts_features, inputs_embeds, input_ids, attention_mask, labels, patch_cnt ) if cache_position is not None: cache_position = torch.arange( attention_mask.size(-1) - inputs_embeds.size(1), attention_mask.size(-1), device=inputs_embeds.device )
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) # if str(input_ids.device) == 'cuda:0': # print(f"[after] {inputs_embeds.shape=}, {attention_mask.sum(-1)=}, {position_ids.max(-1)=}, {cache_position.max().item()=}") outputs: BaseModelOutputWithPast = self.model( attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, cache_position=cache_position, **kwargs, )
hidden_states = outputs.last_hidden_state # Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :])
loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs) # print(f"{logits.shape=}, {hidden_states.shape=}, {slice_indices=}, {logits_to_keep=}, labels={(labels != self.config.ignore_index).sum() if labels is not None else None}, {loss=}, {torch.sum(torch.isnan(logits))=}, {torch.sum(torch.isinf(logits))=}, {torch.sum(torch.isnan(hidden_states))=}, {torch.sum(torch.isinf(hidden_states))=}")
return Qwen3TSCausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, last_hidden_state=hidden_states, hidden_states=outputs.hidden_states, attentions=outputs.attentions, attention_mask=attention_mask, labels=labels, new_token_positions=new_token_positions if timeseries is not None and timeseries.shape[0] > 0 else None, )
__all__ = [ "Qwen3TSForCausalLM"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224# coding=utf-8# Copyright 2024 Tsinghua University and ByteDance.## Licensed under the MIT License (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://opensource.org/license/mit## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import numpy as npfrom typing import List, Union, Tuple, Optionalimport torch
from transformers.feature_extraction_utils import BatchFeaturefrom transformers.processing_utils import ProcessorMixinfrom transformers.tokenization_utils_base import PaddingStrategy
def sp_encoding(timeseries: np.ndarray, eots_token: bool = True) -> Tuple[np.ndarray, str, dict]: """ Encodes a time series with scalar normalization.
Args: timeseries (np.ndarray): The raw time series data (1D or 2D).
Returns: result_timeseries (np.ndarray): The encoded time series, shape [seq_len, 1]. prompt (str): The placeholder string with offset and scaling info. metadata (dict): Metadata containing the offset and scaling factor. """ timeseries = np.array(timeseries) mean = np.mean(timeseries) scaled_timeseries = timeseries - mean scale_factor = 1.0 if np.any(np.abs(scaled_timeseries) >= 3.0): scale_factor = np.max(np.abs(scaled_timeseries)) / 3.0 scaled_timeseries /= scale_factor
prompt = f"[offset={-mean:.4f}|scaling={scale_factor:.4f}|length={len(timeseries)}|max={max(timeseries):.4f}|min={min(timeseries):.4f}|left={timeseries[0]:.4f}|right={timeseries[-1]:.4f}]<ts>" if eots_token: prompt += '<ts/>'
result_timeseries = np.stack([scaled_timeseries, np.ones_like(scaled_timeseries)], axis=-1).reshape(-1, 1)
return result_timeseries, prompt, {"offset": float(-mean), "scale_factor": float(scale_factor)}
class Qwen3TSProcessor(ProcessorMixin): """ A processor for ChatTS that integrates text prompt processing and time series encoding. """
attributes = ["tokenizer"] feature_extractor_class = None # You can add a feature extractor if needed tokenizer_class = "AutoTokenizer"
def __init__(self, tokenizer=None, chat_template=None, **kwargs): """ Args: tokenizer: An optional tokenizer to process text prompts. """ if chat_template is None and tokenizer is not None and tokenizer.chat_template is not None: chat_template = tokenizer.chat_template self.chat_template = chat_template
super().__init__(tokenizer=tokenizer, chat_template=chat_template, **kwargs)
def __call__( self, text: Union[str, List[str]], timeseries: Optional[List[List[np.ndarray]]] = None, padding: Union[bool, str, PaddingStrategy] = False, padding_side: str = 'left', vllm_flag: bool = False, tokenize: bool = True, **kwargs, ) -> BatchFeature: """ Encodes a prompt and its associated time series.
Args: prompt (List[str]): The input prompt containing <ts><ts/> placeholders. timeseries (List[np.ndarray]): A list of time series matched to placeholders in the prompt. padding (bool or str or PaddingStrategy, optional): Passed to the tokenizer for text padding. return_tensors (str, optional): "pt" to return PyTorch tensors; None to return NumPy arrays. **kwargs: Additional tokenizer parameters.
Returns: BatchFeature: Contains processed prompt, encoded time series, and tokenizer outputs. """ if type(text) == str: text = [text] if timeseries is None: timeseries = []
reconstructed_prompts = [] concatenated_ts = None ts_tokens = []
if vllm_flag: # All prompt modifications have to be done inside of the vLLM # to work correctly with its caching mechanism. reconstructed_prompts = text # Process timeseries data encoded_ts_arrays = [] for ts in timeseries: # Get the normalized data and prompt text encoded_ts, ts_prompt, _ = sp_encoding(ts, eots_token=False) # Tokenize the ts_prompt and add to the tokens list if self.tokenizer is not None: tokens = self.tokenizer.encode(ts_prompt, add_special_tokens=False) ts_tokens.append(tokens) encoded_ts_arrays.append(encoded_ts[None, ...]) else: encoded_ts_arrays = [] total_ts_cnt = 0 for idx, prompt in enumerate(text): # Split prompt by <ts><ts/> placeholders last_ts_cnt = total_ts_cnt prompt_segments = prompt.split("<ts><ts/>") total_ts_cnt = total_ts_cnt + len(prompt_segments) - 1
# Encode each time series and rebuild the prompt reconstructed_prompt = prompt_segments[0]
for i, ts in enumerate(timeseries[last_ts_cnt:total_ts_cnt]): encoded_ts, ts_prompt, _ = sp_encoding(ts, eots_token=not vllm_flag) reconstructed_prompt += ts_prompt + prompt_segments[i + 1] # Ensure time series shape [1, seq_len, feature_dim] for batch concatenation encoded_ts_arrays.append(encoded_ts[None, ...])
reconstructed_prompts.append(reconstructed_prompt)
if len(timeseries) != len(encoded_ts_arrays): raise ValueError( f"Mismatch between <ts><ts/> placeholders ({total_ts_cnt}) " f"and time series ({len(encoded_ts_arrays)})." )
if len(encoded_ts_arrays) > 0: # Pad time series to the same length max_length = max(ts.shape[1] for ts in encoded_ts_arrays) padded_ts_arrays = [ np.pad(ts, ((0, 0), (0, max_length - ts.shape[1]), (0, 0)), mode="constant", constant_values=0.0) for ts in encoded_ts_arrays ] concatenated_ts = np.concatenate(padded_ts_arrays, axis=0) # Shape: [batch_size, max_length, feature_dim] # Convert to torch concatenated_ts = torch.from_numpy(concatenated_ts).half()
# Tokenize the processed prompt tokenizer_outputs = {} if tokenize and self.tokenizer is not None: tokenizer_outputs = self.tokenizer(reconstructed_prompts, padding=padding, padding_side=padding_side, **kwargs) else: tokenizer_outputs = {"text": reconstructed_prompts}
# Create the final output outputs = tokenizer_outputs if vllm_flag: outputs["timeseries"] = zip(ts_tokens, encoded_ts_arrays) elif concatenated_ts is not None: outputs["timeseries"] = concatenated_ts
return BatchFeature(data=outputs)
def encode_timeseries( self, timeseries: Optional[List[List[np.ndarray]]] = None, ) -> np.ndarray: if timeseries is None: timeseries = []
concatenated_ts = None encoded_ts_arrays = []
for i, ts in enumerate(timeseries): encoded_ts, _, _ = sp_encoding(ts) # Ensure time series shape [1, seq_len, feature_dim] for batch concatenation encoded_ts_arrays.append(encoded_ts[None, ...])
if len(encoded_ts_arrays) > 0: # Pad time series to the same length max_length = max(ts.shape[1] for ts in encoded_ts_arrays) padded_ts_arrays = [ np.pad(ts, ((0, 0), (0, max_length - ts.shape[1]), (0, 0)), mode="constant", constant_values=0.0) for ts in encoded_ts_arrays ] concatenated_ts = np.concatenate(padded_ts_arrays, axis=0) # Shape: [batch_size, max_length, feature_dim] # Convert to torch concatenated_ts = torch.from_numpy(concatenated_ts).half()
return concatenated_ts
@property def model_input_names(self): """ Define the input names expected by the model. """ tokenizer_input_names = [] if self.tokenizer and hasattr(self.tokenizer, "model_input_names"): tokenizer_input_names = self.tokenizer.model_input_names return list(dict.fromkeys(["processed_prompt", "time_series"] + tokenizer_input_names))
def batch_decode(self, *args, **kwargs): """ This method forwards all its arguments to Qwen3TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please refer to the docstring of this method for more information. """ return self.tokenizer.batch_decode(*args, **kwargs)
def decode(self, *args, **kwargs): """ This method forwards all its arguments to Qwen3TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to the docstring of this method for more information. """ return self.tokenizer.decode(*args, **kwargs)123456{ "auto_map": { "AutoProcessor": "processing_qwen3_ts.Qwen3TSProcessor" }, "processor_class": "Qwen3TSProcessor"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425{ "metadata": { "total_parameters": 347136, "total_size": 16550696992 }, "weight_map": { "codi_mae_applier.mask_token": "pytorch_model-00004-of-00004.bin", "codi_projection.1.bias": "pytorch_model-00004-of-00004.bin", "codi_projection.1.weight": "pytorch_model-00004-of-00004.bin", "codi_projection.3.bias": "pytorch_model-00004-of-00004.bin", "codi_projection.3.weight": "pytorch_model-00004-of-00004.bin", "codi_projection.ln.bias": "pytorch_model-00004-of-00004.bin", "codi_projection.ln.weight": "pytorch_model-00004-of-00004.bin", "lm_head.weight": "pytorch_model-00004-of-00004.bin", "model.embed_tokens.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.0.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.1.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.10.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.10.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.11.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.12.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.13.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.14.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.15.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.16.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.17.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.18.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.19.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.2.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.2.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.20.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.20.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.mlp.gate_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.21.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.22.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.22.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.22.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.22.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.22.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.22.self_attn.k_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.22.self_attn.k_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.22.self_attn.o_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.22.self_attn.q_norm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.22.self_attn.q_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.22.self_attn.v_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.23.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.23.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.24.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.25.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.26.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.27.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.28.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.29.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.3.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.3.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.30.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.30.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.31.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.32.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.33.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.input_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.mlp.down_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.mlp.gate_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.mlp.up_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.post_attention_layernorm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.self_attn.k_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.self_attn.o_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.self_attn.q_norm.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.34.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.35.input_layernorm.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.mlp.down_proj.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.mlp.gate_proj.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.mlp.up_proj.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.post_attention_layernorm.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.self_attn.k_norm.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.self_attn.k_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.35.self_attn.o_proj.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.self_attn.q_norm.weight": "pytorch_model-00004-of-00004.bin", "model.layers.35.self_attn.q_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.35.self_attn.v_proj.weight": "pytorch_model-00003-of-00004.bin", "model.layers.4.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.4.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.5.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.6.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.7.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.input_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.mlp.down_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.mlp.up_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.post_attention_layernorm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.8.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.9.input_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.9.mlp.down_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.9.mlp.gate_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.9.mlp.up_proj.weight": "pytorch_model-00002-of-00004.bin", "model.layers.9.post_attention_layernorm.weight": "pytorch_model-00002-of-00004.bin", "model.layers.9.self_attn.k_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.9.self_attn.k_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.9.self_attn.o_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.9.self_attn.q_norm.weight": "pytorch_model-00001-of-00004.bin", "model.layers.9.self_attn.q_proj.weight": "pytorch_model-00001-of-00004.bin", "model.layers.9.self_attn.v_proj.weight": "pytorch_model-00001-of-00004.bin", "model.norm.weight": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.0.bias": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.0.weight": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.2.bias": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.2.weight": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.4.bias": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.4.weight": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.6.bias": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.6.weight": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.8.bias": "pytorch_model-00004-of-00004.bin", "ts_encoder.mlp.8.weight": "pytorch_model-00004-of-00004.bin", "ts_encoder.position_embedding.weight": "pytorch_model-00004-of-00004.bin" }}1234567891011121314151617181920{ "additional_special_tokens": [ "<ts>", "<ts/>" ], "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 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265{ "add_bos_token": false, "add_prefix_space": false, "added_tokens_decoder": { "151643": { "content": "<|endoftext|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151644": { "content": "<|im_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151645": { "content": "<|im_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151646": { "content": "<|object_ref_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151647": { "content": "<|object_ref_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151648": { "content": "<|box_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151649": { "content": "<|box_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151650": { "content": "<|quad_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151651": { "content": "<|quad_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151652": { "content": "<|vision_start|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151653": { "content": "<|vision_end|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151654": { "content": "<|vision_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151655": { "content": "<|image_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151656": { "content": "<|video_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151657": { "content": "<tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151658": { "content": "</tool_call>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151659": { "content": "<|fim_prefix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151660": { "content": "<|fim_middle|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151661": { "content": "<|fim_suffix|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151662": { "content": "<|fim_pad|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151663": { "content": "<|repo_name|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151664": { "content": "<|file_sep|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151665": { "content": "<tool_response>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151666": { "content": "</tool_response>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151667": { "content": "<think>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151668": { "content": "</think>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": false }, "151669": { "content": "<ts>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151670": { "content": "<ts/>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151671": { "content": "<|bot|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "151672": { "content": "<|eot|>", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true } }, "additional_special_tokens": [ "<ts>", "<ts/>" ], "auto_map": { "AutoProcessor": "processing_qwen3_ts.Qwen3TSProcessor" }, "bos_token": null, "clean_up_tokenization_spaces": false, "eos_token": "<|im_end|>", "errors": "replace", "extra_special_tokens": {}, "model_max_length": 131072, "pad_token": "<|endoftext|>", "padding_side": "right", "processor_class": "Qwen3TSProcessor", "split_special_tokens": false, "tokenizer_class": "Qwen2Tokenizer", "unk_token": null}1234567891011121314151617181920212223242526272829303132{ "</think>": 151668, "</tool_call>": 151658, "</tool_response>": 151666, "<think>": 151667, "<tool_call>": 151657, "<tool_response>": 151665, "<ts/>": 151670, "<ts>": 151669, "<|bot|>": 151671, "<|box_end|>": 151649, "<|box_start|>": 151648, "<|endoftext|>": 151643, "<|eot|>": 151672, "<|file_sep|>": 151664, "<|fim_middle|>": 151660, "<|fim_pad|>": 151662, "<|fim_prefix|>": 151659, "<|fim_suffix|>": 151661, "<|im_end|>": 151645, "<|im_start|>": 151644, "<|image_pad|>": 151655, "<|object_ref_end|>": 151647, "<|object_ref_start|>": 151646, "<|quad_end|>": 151651, "<|quad_start|>": 151650, "<|repo_name|>": 151663, "<|video_pad|>": 151656, "<|vision_end|>": 151653, "<|vision_pad|>": 151654, "<|vision_start|>": 151652}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889{%- if tools %} {{- '<|im_start|>system\n' }} {%- if messages[0].role == 'system' %} {{- messages[0].content + '\n\n' }} {%- 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' }} {%- 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 message.content is string 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.content is string %} {%- set content = message.content %} {%- else %} {%- set content = '' %} {%- endif %} {%- if (message.role == "user") or (message.role == "system" and not loop.first) %} {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} {%- elif message.role == "assistant" %} {%- set reasoning_content = '' %} {%- if message.reasoning_content is string %} {%- set reasoning_content = message.reasoning_content %} {%- else %} {%- if '</think>' in content %} {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %} {%- set content = content.split('</think>')[-1].lstrip('\n') %} {%- endif %} {%- endif %} {%- if loop.index0 > ns.last_query_index %} {%- if loop.last or (not loop.last and reasoning_content) %} {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }} {%- else %} {{- '<|im_start|>' + message.role + '\n' + content }} {%- endif %} {%- else %} {{- '<|im_start|>' + message.role + '\n' + content }} {%- endif %} {%- 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' }} {{- 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' }} {%- if enable_thinking is defined and enable_thinking is false %} {{- '<think>\n\n</think>\n\n' }} {%- endif %}{%- endif %}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990{ "architectures": [ "Qwen3TSForCausalLM" ], "attention_bias": false, "attention_dropout": 0.0, "auto_map": { "AutoConfig": "configuration_qwen3_ts.Qwen3TSConfig", "AutoModel": "modeling_qwen3_ts.Qwen3TSForCausalLM", "AutoModelForCausalLM": "modeling_qwen3_ts.Qwen3TSForCausalLM", "AutoProcessor": "processing_qwen3_ts.Qwen3TSProcessor" }, "bos_token_id": 151643, "eos_token_id": 151645, "head_dim": 128, "hidden_act": "silu", "hidden_size": 4096, "ignore_index": -100, "initializer_range": 0.02, "intermediate_size": 12288, "layer_types": [ "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention", "full_attention" ], "max_position_embeddings": 40960, "max_window_layers": 36, "model_type": "qwen3ts", "num_attention_heads": 32, "num_hidden_layers": 36, "num_key_value_heads": 8, "pad_token_id": 151643, "rms_norm_eps": 1e-06, "rope_scaling": null, "rope_theta": 1000000, "sliding_window": null, "tie_word_embeddings": false, "torch_dtype": "bfloat16", "transformers_version": "4.54.1", "ts": { "embedding_dim": 16, "hidden_size": 4096, "max_length": 32768, "max_sequence_length": 8192, "num_features": 2, "num_layers": 5, "patch_size": 8, "use_layer_norm": false, "use_position_embedding": true, "use_position_idx": false }, "ts_token_end_index": 151670, "ts_token_start_index": 151669, "use_cache": false, "use_sliding_window": false, "vocab_size": 151936}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225# coding=utf-8# Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License."""Qwen3 model configuration"""
from transformers.configuration_utils import PretrainedConfigfrom transformers.modeling_rope_utils import rope_config_validationfrom transformers.utils import logging
logger = logging.get_logger(__name__)
class Qwen3TSConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`Qwen3Model`]. It is used to instantiate a Qwen3 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of Qwen3-8B [Qwen/Qwen3-8B](https://huggingface.co/Qwen/Qwen3-8B).
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.
Args: vocab_size (`int`, *optional*, defaults to 151936): Vocabulary size of the Qwen3 model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`Qwen3Model`] hidden_size (`int`, *optional*, defaults to 4096): Dimension of the hidden representations. intermediate_size (`int`, *optional*, defaults to 22016): Dimension of the MLP representations. num_hidden_layers (`int`, *optional*, defaults to 32): Number of hidden layers in the Transformer encoder. num_attention_heads (`int`, *optional*, defaults to 32): Number of attention heads for each attention layer in the Transformer encoder. num_key_value_heads (`int`, *optional*, defaults to 32): This is the number of key_value heads that should be used to implement Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details, check out [this paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`. head_dim (`int`, *optional*, defaults to 128): The attention head dimension. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`): The non-linear activation function (function or string) in the decoder. max_position_embeddings (`int`, *optional*, defaults to 32768): The maximum sequence length that this model might ever be used with. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. rms_norm_eps (`float`, *optional*, defaults to 1e-06): The epsilon used by the rms normalization layers. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True`. tie_word_embeddings (`bool`, *optional*, defaults to `False`): Whether the model's input and output word embeddings should be tied. rope_theta (`float`, *optional*, defaults to 10000.0): The base period of the RoPE embeddings. rope_scaling (`Dict`, *optional*): Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value accordingly. Expected contents: `rope_type` (`str`): The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope', 'llama3'], with 'default' being the original RoPE implementation. `factor` (`float`, *optional*): Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In most scaling types, a `factor` of x will enable the model to handle sequences of length x * original maximum pre-trained length. `original_max_position_embeddings` (`int`, *optional*): Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during pretraining. `attention_factor` (`float`, *optional*): Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention computation. If unspecified, it defaults to value recommended by the implementation, using the `factor` field to infer the suggested value. `beta_fast` (`float`, *optional*): Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear ramp function. If unspecified, it defaults to 32. `beta_slow` (`float`, *optional*): Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear ramp function. If unspecified, it defaults to 1. `short_factor` (`list[float]`, *optional*): Only used with 'longrope'. The scaling factor to be applied to short contexts (< `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 `long_factor` (`list[float]`, *optional*): Only used with 'longrope'. The scaling factor to be applied to long contexts (< `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 `low_freq_factor` (`float`, *optional*): Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE `high_freq_factor` (`float`, *optional*): Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`): Whether to use a bias in the query, key, value and output projection layers during self-attention. use_sliding_window (`bool`, *optional*, defaults to `False`): Whether to use sliding window attention. sliding_window (`int`, *optional*, defaults to 4096): Sliding window attention (SWA) window size. If not specified, will default to `4096`. max_window_layers (`int`, *optional*, defaults to 28): The number of layers using full attention. The first `max_window_layers` layers will use full attention, while any additional layer afterwards will use SWA (Sliding Window Attention). layer_types (`list`, *optional*): Attention pattern for each layer. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities.
```python >>> from transformers import Qwen3Model, Qwen3Config
>>> # Initializing a Qwen3 style configuration >>> configuration = Qwen3Config()
>>> # Initializing a model from the Qwen3-8B style configuration >>> model = Qwen3Model(configuration)
>>> # Accessing the model configuration >>> configuration = model.config ```"""
model_type = "qwen3ts" keys_to_ignore_at_inference = ["past_key_values"]
# Default tensor parallel plan for base model `Qwen3` base_model_tp_plan = { "layers.*.self_attn.q_proj": "colwise", "layers.*.self_attn.k_proj": "colwise", "layers.*.self_attn.v_proj": "colwise", "layers.*.self_attn.o_proj": "rowwise", "layers.*.mlp.gate_proj": "colwise", "layers.*.mlp.up_proj": "colwise", "layers.*.mlp.down_proj": "rowwise", } base_model_pp_plan = { "embed_tokens": (["input_ids"], ["inputs_embeds"]), "layers": (["hidden_states", "attention_mask"], ["hidden_states"]), "norm": (["hidden_states"], ["hidden_states"]), }
def __init__( self, vocab_size=151936, hidden_size=4096, intermediate_size=22016, num_hidden_layers=32, num_attention_heads=32, num_key_value_heads=32, head_dim=128, hidden_act="silu", max_position_embeddings=32768, initializer_range=0.02, rms_norm_eps=1e-6, use_cache=True, tie_word_embeddings=False, rope_theta=10000.0, rope_scaling=None, attention_bias=False, use_sliding_window=False, sliding_window=4096, max_window_layers=28, layer_types=None, attention_dropout=0.0, **kwargs, ): self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.use_sliding_window = use_sliding_window self.sliding_window = sliding_window if self.use_sliding_window else None self.max_window_layers = max_window_layers
# for backward compatibility if num_key_value_heads is None: num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads self.head_dim = head_dim self.hidden_act = hidden_act self.initializer_range = initializer_range self.rms_norm_eps = rms_norm_eps self.use_cache = use_cache self.rope_theta = rope_theta self.rope_scaling = rope_scaling self.attention_bias = attention_bias self.attention_dropout = attention_dropout # Validate the correctness of rotary position embeddings parameters # BC: if there is a 'type' field, move it to 'rope_type'. if self.rope_scaling is not None and "type" in self.rope_scaling: self.rope_scaling["rope_type"] = self.rope_scaling["type"] rope_config_validation(self)
self.layer_types = layer_types if self.layer_types is None: self.layer_types = [ "sliding_attention" if self.sliding_window is not None and i >= self.max_window_layers else "full_attention" for i in range(self.num_hidden_layers) ]
super().__init__( tie_word_embeddings=tie_word_embeddings, **kwargs, )
__all__ = ["Qwen3TSConfig"]12345678910111213{ "bos_token_id": 151643, "do_sample": true, "eos_token_id": [ 151645, 151643 ], "pad_token_id": 151643, "temperature": 0.6, "top_k": 20, "top_p": 0.95, "transformers_version": "4.54.1"}123456789101112{ "stage": "lapras", "template": "chatts", "ts_patch_size": 8, "answer_anchor": "Answer:", "use_cot": null, "num_latent": 6, "projection": { "projection_dim": 2048 }, "remove_eos": true}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601# Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
from typing import Callable, Optional, Union
import torchfrom torch import nnfrom dataclasses import dataclass
from transformers.cache_utils import Cachefrom transformers.generation import GenerationMixinfrom transformers.modeling_flash_attention_utils import FlashAttentionKwargsfrom transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast)from transformers.models.qwen3.modeling_qwen3 import Qwen3PreTrainedModel, Qwen3Modelfrom transformers.modeling_utils import PreTrainedModelfrom transformers.processing_utils import Unpackfrom transformers.utils import auto_docstring, can_return_tuple, logging, ModelOutputfrom .configuration_qwen3_ts import Qwen3TSConfigfrom typing import Any, Dict
logger = logging.get_logger(__name__)
########################MLP TS Embedding#####################class TimeSeriesEmbedding(nn.Module): def __init__(self, config): super(TimeSeriesEmbedding, self).__init__() self.patch_size = config['patch_size'] self.num_layers = config['num_layers'] self.hidden_size = config['hidden_size'] self.num_features = config['num_features'] self.max_sequence_length = config['max_sequence_length'] # Maximum time series length self.use_position_embedding = config.get('use_position_embedding', False) self.use_position_idx = config.get('use_position_idx', False) self.use_layer_norm = config.get('use_layer_norm', False) self.embedding_dim = config.get('embedding_dim', 16) # Embedding dimension if self.use_position_embedding: # Extended vocabulary: [0, max_sequence_length) for real positions, max_sequence_length for padding self.position_embedding = nn.Embedding(self.max_sequence_length + 1, self.embedding_dim) self.padding_idx = self.max_sequence_length # Special index for padding input_size = 1 * self.patch_size + self.embedding_dim * self.patch_size elif self.use_position_idx: input_size = 2 * self.patch_size else: input_size = 1 * self.patch_size # Build MLP layers layers = [] for _ in range(self.num_layers - 1): layers.append(nn.Linear(input_size, self.hidden_size)) layers.append(nn.GELU()) input_size = self.hidden_size
layers.append(nn.Linear(input_size, self.hidden_size)) if self.use_layer_norm: layers.append(nn.LayerNorm(self.hidden_size))
self.mlp = nn.Sequential(*layers)
def forward(self, x: torch.Tensor): batch_size = x.size(0) x = x.reshape(batch_size, -1, self.num_features)
# Extract mask and calculate valid lengths mask = x[:, :, -1].long() valid_lengths = mask.sum(dim=1).long() patch_cnt = (valid_lengths + self.patch_size - 1) // self.patch_size
patches_list = [] # Collect position indices for batch embedding lookup all_position_indices = [] patch_info_list = [] # Store metadata for each patch group for i in range(batch_size): vl = valid_lengths[i].item() pc = patch_cnt[i].item() if pc == 0: continue # Extract time series data (excluding mask) xi = x[i, :vl, :1] # Time-series data total_padded_length = pc * self.patch_size padding_length = total_padded_length - vl # Create position indices: real positions for actual data, special index for padding position_indices = torch.arange(vl, device=x.device) if padding_length > 0: # Pad with last value last_value = xi[-1:, :] padding = last_value.repeat(padding_length, 1) xi = torch.cat([xi, padding], dim=0) # Use special padding index for padding positions padding_positions = torch.full((padding_length,), self.padding_idx, device=x.device) position_indices = torch.cat([position_indices, padding_positions], dim=0)
# Reshape to patches xi = xi.reshape(pc, self.patch_size) # (num_patches, patch_size) position_indices = position_indices.reshape(pc, self.patch_size) # (num_patches, patch_size)
if self.use_position_embedding: # Collect position indices instead of calling embedding immediately all_position_indices.append(position_indices) patch_info_list.append({ 'xi': xi, 'pc': pc, 'sample_idx': i }) elif self.use_position_idx: # Normalize position indices pos_indices = torch.arange(vl, device=x.device).unsqueeze(1) pos_indices = pos_indices / max(1, valid_lengths.max().item() - 1) if padding_length > 0: # Use -1 for padding positions padding_indices = torch.full((padding_length, 1), -1, device=x.device) pos_indices = torch.cat([pos_indices, padding_indices], dim=0) # Combine time series data with position indices xi_combined = torch.cat([xi.reshape(-1, 1), pos_indices], dim=1) patch_input = xi_combined.reshape(pc, self.patch_size * 2) patches_list.append(patch_input) else: # No position embedding, use raw patches patch_input = xi patches_list.append(patch_input)
# Batch process position embeddings if needed if self.use_position_embedding and all_position_indices: # Concatenate all position indices for batch embedding lookup batch_position_indices = torch.cat(all_position_indices, dim=0) # print(f"{x.shape=}, {x.device=}, {len(all_position_indices)=}, {batch_position_indices=}") batch_pos_emb = self.position_embedding(batch_position_indices) # Single embedding call # Split embeddings back and create patch inputs emb_start_idx = 0 for patch_info in patch_info_list: xi = patch_info['xi'] pc = patch_info['pc'] # Extract corresponding embeddings pos_emb = batch_pos_emb[emb_start_idx:emb_start_idx + pc] emb_start_idx += pc # Flatten and concatenate xi = xi.unsqueeze(-1) # (num_patches, patch_size, 1) patch_input = torch.cat([ xi.flatten(1), # (num_patches, patch_size) pos_emb.flatten(1) # (num_patches, patch_size * embedding_dim) ], dim=1) patches_list.append(patch_input)
# Process all patches through MLP if patches_list: x_patches = torch.cat(patches_list, dim=0) x = self.mlp(x_patches) else: # Handle empty case x = torch.empty(0, self.hidden_size, device=x.device)
return x, patch_cnt
@dataclassclass Qwen3TSCausalLMOutputWithPast(CausalLMOutputWithPast): """ Output type of Qwen3TSForCausalLM that includes additional fields for timeseries processing. Args: loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Language modeling loss (for next-token prediction). logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed): Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*): The attention mask used in the forward pass, potentially expanded to accommodate timeseries patches. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. new_token_positions (`torch.LongTensor` of shape `(batch_size, num_new_tokens)`, *optional*): Positions where new tokens (not from timeseries) are located in the expanded sequence. """ last_hidden_state: Optional[torch.FloatTensor] = None attention_mask: Optional[torch.FloatTensor] = None labels: Optional[torch.LongTensor] = None new_token_positions: Optional[torch.LongTensor] = None
class Qwen3TSGenerationMixin(GenerationMixin): """ Generation mixin for Qwen3 models with timeseries support. This mixin handles the special case where timeseries embeddings expand the sequence length during the first forward pass, requiring special attention mask management. """ def prepare_inputs_for_generation( self, input_ids: torch.LongTensor, past_key_values: Optional[Cache] = None, attention_mask: Optional[torch.LongTensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, cache_position: Optional[torch.LongTensor] = None, timeseries: Optional[torch.FloatTensor] = None, **kwargs, ) -> Dict[str, Any]: """ Prepare inputs for generation with timeseries support. Timeseries are only processed during the first forward pass. In subsequent generation steps, they are already embedded in the past_key_values. """ # Check if we have timeseries data has_ts = timeseries is not None and len(timeseries) > 0 # Handle timeseries for generation with past_key_values if has_ts and past_key_values is not None: # Get the number of tokens already processed if isinstance(past_key_values, Cache): if hasattr(past_key_values, 'seen_tokens'): past_length = past_key_values.seen_tokens else: past_length = past_key_values.get_seq_length() else: past_length = past_key_values[0][0].shape[2] if past_key_values[0] is not None else 0 # If we have processed tokens, timeseries have already been embedded if past_length > 0: # Only keep the last token for next token prediction input_ids = input_ids[:, -1:] # Clear timeseries as they've been processed timeseries = None has_ts = False # Call parent's prepare_inputs_for_generation to handle all standard logic # print(f"[debug] {input_ids.shape=}, {attention_mask.shape=}, {cache_position.max()=}, {past_length=}, {has_ts=}") model_inputs = super().prepare_inputs_for_generation( input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, inputs_embeds=inputs_embeds, cache_position=cache_position, **kwargs ) # Add timeseries to model inputs model_inputs["timeseries"] = timeseries return model_inputs def _update_model_kwargs_for_generation( self, outputs: ModelOutput, model_kwargs: Dict[str, Any], is_encoder_decoder: bool = False, num_new_tokens: int = 1, ) -> Dict[str, Any]: """ Update model keyword arguments for generation, handling attention mask from outputs. This is necessary because timeseries processing can expand the sequence length, and we need to use the expanded attention_mask from the model outputs. """ # Handle special case: use attention_mask from outputs if available # This is crucial for timeseries models where the sequence length is expanded if hasattr(outputs, "attention_mask") and outputs.attention_mask is not None: model_kwargs["attention_mask"] = outputs.attention_mask # Call parent's implementation for standard updates model_kwargs = super()._update_model_kwargs_for_generation( outputs=outputs, model_kwargs=model_kwargs, is_encoder_decoder=is_encoder_decoder, num_new_tokens=num_new_tokens, ) return model_kwargs def generate( self, inputs: Optional[torch.Tensor] = None, timeseries: Optional[torch.FloatTensor] = None, generation_config=None, **kwargs, ): """ Generate sequences with timeseries support. Args: inputs: Input token ids timeseries: Optional timeseries data to be processed in the first forward pass generation_config: Generation configuration **kwargs: Additional keyword arguments for generation """ # Add timeseries to kwargs if provided if timeseries is not None: kwargs["timeseries"] = timeseries # Call parent's generate method return super().generate( inputs=inputs, generation_config=generation_config, **kwargs, ) def _validate_model_kwargs(self, model_kwargs: Dict[str, Any]) -> None: """ Validate model kwargs, allowing timeseries as a valid argument. """ # Remove timeseries from model_kwargs temporarily for validation timeseries = model_kwargs.pop("timeseries", None) # Call parent's validation super()._validate_model_kwargs(model_kwargs) # Restore timeseries if timeseries is not None: model_kwargs["timeseries"] = timeseries
class Qwen3TSPreTrainedModel(Qwen3PreTrainedModel): config_class = Qwen3TSConfig
@auto_docstringclass Qwen3TSForCausalLM(Qwen3TSPreTrainedModel, Qwen3TSGenerationMixin): _tied_weights_keys = ["lm_head.weight"] _tp_plan = {"lm_head": "colwise_rep"} _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config): super().__init__(config) self.model = Qwen3Model(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# TS embedding self.ts_encoder = TimeSeriesEmbedding(config.ts)
# Initialize weights and apply final processing 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 merge_ununiform_ts(self, time_series_features, inputs_embeds, input_ids, attention_mask, labels, patch_cnt): """Merge the TS patch embeddings into the token sequence; rows may hold different patch counts.""" batch_size, sequence_length = input_ids.shape device = input_ids.device
_left_padding = torch.any(attention_mask[:, 0] == 0) _right_padding = torch.any(attention_mask[:, -1] == 0) if _left_padding and _right_padding: raise ValueError(f"both side of attention_mask has zero, invalid. {attention_mask}") left_padding = bool(_left_padding and not _right_padding)
start_mask = input_ids == self.config.ts_token_start_index marker_mask = start_mask | (input_ids == self.config.ts_token_end_index) real = attention_mask.bool()
patch_cnt = patch_cnt.to(device) num_ts_row = start_mask.sum(dim=-1) # series per row n_series = int(num_ts_row.sum()) if n_series != patch_cnt.numel(): raise ValueError( f"{n_series} <ts> markers in the batch but {patch_cnt.numel()} patch counts" )
# Slots each row gains: a series takes patch_cnt slots and already owns its two markers. row_of_series = torch.repeat_interleave(torch.arange(batch_size, device=device), num_ts_row) patches_row = torch.zeros(batch_size, dtype=torch.long, device=device).index_add_( 0, row_of_series, patch_cnt ) num_total_patches = patches_row - 2 * num_ts_row
grow = torch.zeros(batch_size, sequence_length, dtype=torch.long, device=device) grow[start_mask] = patch_cnt - 2 # start_mask.nonzero() is row-major, matching patch_cnt
# Destination of every token within its own row. rank = (real.long().cumsum(dim=-1) - 1).clamp(min=0) # real tokens before this one grow_real = grow * real growth_before = grow_real.cumsum(dim=-1) - grow_real # exclusive prefix sum dest = rank + growth_before
own_len = real.sum(dim=-1) + num_total_patches # expanded length per row max_embed_dim = sequence_length + int(num_total_patches.max()) offset = (max_embed_dim - own_len) if left_padding else torch.zeros_like(own_len) dest = dest + offset[:, None] # the single padding step
# Text tokens; the markers and padding are not placed. final_embedding = torch.zeros( batch_size, max_embed_dim, inputs_embeds.size(-1), dtype=inputs_embeds.dtype, device=inputs_embeds.device, ) text_sel = real & ~marker_mask t_batch, t_pos = text_sel.nonzero(as_tuple=True) final_embedding[t_batch, dest[t_batch, t_pos]] = inputs_embeds[t_batch, t_pos]
final_labels = None if labels is not None: final_labels = torch.full( (batch_size, max_embed_dim), self.config.ignore_index, dtype=labels.dtype, device=labels.device, ) final_labels[t_batch, dest[t_batch, t_pos]] = labels[t_batch, t_pos]
# Patches: one contiguous block per series, starting at its <ts> destination. s_batch, s_pos = start_mask.nonzero(as_tuple=True) block_start = dest[s_batch, s_pos] total_patches = int(patch_cnt.sum()) if time_series_features.shape[0] != total_patches: raise ValueError( f"The input provided to the model are wrong. patch_cnt sums to {total_patches} " f"but {time_series_features.shape[0]} time-series features were given. " "This prevents correct indexing and breaks batch generation." ) series_id = torch.repeat_interleave(torch.arange(n_series, device=device), patch_cnt) within = torch.arange(total_patches, device=device) - torch.repeat_interleave( patch_cnt.cumsum(0) - patch_cnt, patch_cnt ) final_embedding[s_batch[series_id], block_start[series_id] + within] = ( time_series_features.contiguous().to(final_embedding.dtype) )
# Attention mask, positions and the input -> expanded index map. ar = torch.arange(max_embed_dim, device=device)[None, :] final_attention_mask = ( (ar >= offset[:, None]) & (ar < (offset + own_len)[:, None]) ).to(attention_mask.dtype)
position_ids = (final_attention_mask.cumsum(-1) - 1).masked_fill_( final_attention_mask == 0, 1 ) # As in ChatTS, a <ts> marker maps to the end of its patch block. new_token_positions = (dest + grow_real).masked_fill(attention_mask == 0, -1)
return final_embedding, final_attention_mask, position_ids, final_labels, new_token_positions
def _merge_input_ids_with_time_series_features(self, time_series_features, inputs_embeds, input_ids, attention_mask, labels, patch_cnt): """ChatTS's name for :meth:`merge_ununiform_ts`.""" return self.merge_ununiform_ts( time_series_features, inputs_embeds, input_ids, attention_mask, labels, patch_cnt )
@can_return_tuple def forward( self, input_ids: Optional[torch.LongTensor] = None, timeseries: torch.FloatTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs, ) -> Qwen3TSCausalLMOutputWithPast: r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*): Pre-computed hidden-states (key and values in the attention blocks). inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*): Indices depicting the position of the input sequence tokens in the sequence. timeseries (`torch.FloatTensor` of shape `(batch_size, num_patches, patch_size)`, *optional*): Timeseries data to be encoded and merged with text embeddings. Returns: [`Qwen3TSCausalLMOutputWithPast`] or `tuple(torch.FloatTensor)`: The model outputs with potential timeseries-expanded attention mask. """
# if input_ids is not None and timeseries is not None: # # Print the input ts # print("=================================================================") # print("Timeseries shape:", timeseries.shape) # print("=================================================================\n\n") # else: # print("Time series is None!!!!")
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 )
if inputs_embeds is None: inputs_embeds = self.get_input_embeddings()(input_ids)
if timeseries is not None and timeseries.shape[0] > 0: # use_cache = False # print(f"timeseries shape: {timeseries.shape=}, {input_ids.shape=}") ts_features, patch_cnt = self.ts_encoder(timeseries) inputs_embeds = inputs_embeds.to(ts_features.dtype) # if str(input_ids.device) == 'cuda:0': # print(f"-------------------------------------------------------\n[before] {input_ids.shape=}, timeseries={timeseries.shape if timeseries is not None else None}, {attention_mask.sum(-1)=}") inputs_embeds, attention_mask, position_ids, labels, new_token_positions = self.merge_ununiform_ts( ts_features, inputs_embeds, input_ids, attention_mask, labels, patch_cnt ) if cache_position is not None: cache_position = torch.arange( attention_mask.size(-1) - inputs_embeds.size(1), attention_mask.size(-1), device=inputs_embeds.device )
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) # if str(input_ids.device) == 'cuda:0': # print(f"[after] {inputs_embeds.shape=}, {attention_mask.sum(-1)=}, {position_ids.max(-1)=}, {cache_position.max().item()=}") outputs: BaseModelOutputWithPast = self.model( attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, cache_position=cache_position, **kwargs, )
hidden_states = outputs.last_hidden_state # Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :])
loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs) # print(f"{logits.shape=}, {hidden_states.shape=}, {slice_indices=}, {logits_to_keep=}, labels={(labels != self.config.ignore_index).sum() if labels is not None else None}, {loss=}, {torch.sum(torch.isnan(logits))=}, {torch.sum(torch.isinf(logits))=}, {torch.sum(torch.isnan(hidden_states))=}, {torch.sum(torch.isinf(hidden_states))=}")
return Qwen3TSCausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, last_hidden_state=hidden_states, hidden_states=outputs.hidden_states, attentions=outputs.attentions, attention_mask=attention_mask, labels=labels, new_token_positions=new_token_positions if timeseries is not None and timeseries.shape[0] > 0 else None, )
__all__ = [ "Qwen3TSForCausalLM"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224# coding=utf-8# Copyright 2024 Tsinghua University and ByteDance.## Licensed under the MIT License (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://opensource.org/license/mit## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import numpy as npfrom typing import List, Union, Tuple, Optionalimport torch
from transformers.feature_extraction_utils import BatchFeaturefrom transformers.processing_utils import ProcessorMixinfrom transformers.tokenization_utils_base import PaddingStrategy
def sp_encoding(timeseries: np.ndarray, eots_token: bool = True) -> Tuple[np.ndarray, str, dict]: """ Encodes a time series with scalar normalization.
Args: timeseries (np.ndarray): The raw time series data (1D or 2D).
Returns: result_timeseries (np.ndarray): The encoded time series, shape [seq_len, 1]. prompt (str): The placeholder string with offset and scaling info. metadata (dict): Metadata containing the offset and scaling factor. """ timeseries = np.array(timeseries) mean = np.mean(timeseries) scaled_timeseries = timeseries - mean scale_factor = 1.0 if np.any(np.abs(scaled_timeseries) >= 3.0): scale_factor = np.max(np.abs(scaled_timeseries)) / 3.0 scaled_timeseries /= scale_factor
prompt = f"[offset={-mean:.4f}|scaling={scale_factor:.4f}|length={len(timeseries)}|max={max(timeseries):.4f}|min={min(timeseries):.4f}|left={timeseries[0]:.4f}|right={timeseries[-1]:.4f}]<ts>" if eots_token: prompt += '<ts/>'
result_timeseries = np.stack([scaled_timeseries, np.ones_like(scaled_timeseries)], axis=-1).reshape(-1, 1)
return result_timeseries, prompt, {"offset": float(-mean), "scale_factor": float(scale_factor)}
class Qwen3TSProcessor(ProcessorMixin): """ A processor for ChatTS that integrates text prompt processing and time series encoding. """
attributes = ["tokenizer"] feature_extractor_class = None # You can add a feature extractor if needed tokenizer_class = "AutoTokenizer"
def __init__(self, tokenizer=None, chat_template=None, **kwargs): """ Args: tokenizer: An optional tokenizer to process text prompts. """ if chat_template is None and tokenizer is not None and tokenizer.chat_template is not None: chat_template = tokenizer.chat_template self.chat_template = chat_template
super().__init__(tokenizer=tokenizer, chat_template=chat_template, **kwargs)
def __call__( self, text: Union[str, List[str]], timeseries: Optional[List[List[np.ndarray]]] = None, padding: Union[bool, str, PaddingStrategy] = False, padding_side: str = 'left', vllm_flag: bool = False, tokenize: bool = True, **kwargs, ) -> BatchFeature: """ Encodes a prompt and its associated time series.
Args: prompt (List[str]): The input prompt containing <ts><ts/> placeholders. timeseries (List[np.ndarray]): A list of time series matched to placeholders in the prompt. padding (bool or str or PaddingStrategy, optional): Passed to the tokenizer for text padding. return_tensors (str, optional): "pt" to return PyTorch tensors; None to return NumPy arrays. **kwargs: Additional tokenizer parameters.
Returns: BatchFeature: Contains processed prompt, encoded time series, and tokenizer outputs. """ if type(text) == str: text = [text] if timeseries is None: timeseries = []
reconstructed_prompts = [] concatenated_ts = None ts_tokens = []
if vllm_flag: # All prompt modifications have to be done inside of the vLLM # to work correctly with its caching mechanism. reconstructed_prompts = text # Process timeseries data encoded_ts_arrays = [] for ts in timeseries: # Get the normalized data and prompt text encoded_ts, ts_prompt, _ = sp_encoding(ts, eots_token=False) # Tokenize the ts_prompt and add to the tokens list if self.tokenizer is not None: tokens = self.tokenizer.encode(ts_prompt, add_special_tokens=False) ts_tokens.append(tokens) encoded_ts_arrays.append(encoded_ts[None, ...]) else: encoded_ts_arrays = [] total_ts_cnt = 0 for idx, prompt in enumerate(text): # Split prompt by <ts><ts/> placeholders last_ts_cnt = total_ts_cnt prompt_segments = prompt.split("<ts><ts/>") total_ts_cnt = total_ts_cnt + len(prompt_segments) - 1
# Encode each time series and rebuild the prompt reconstructed_prompt = prompt_segments[0]
for i, ts in enumerate(timeseries[last_ts_cnt:total_ts_cnt]): encoded_ts, ts_prompt, _ = sp_encoding(ts, eots_token=not vllm_flag) reconstructed_prompt += ts_prompt + prompt_segments[i + 1] # Ensure time series shape [1, seq_len, feature_dim] for batch concatenation encoded_ts_arrays.append(encoded_ts[None, ...])
reconstructed_prompts.append(reconstructed_prompt)
if len(timeseries) != len(encoded_ts_arrays): raise ValueError( f"Mismatch between <ts><ts/> placeholders ({total_ts_cnt}) " f"and time series ({len(encoded_ts_arrays)})." )
if len(encoded_ts_arrays) > 0: # Pad time series to the same length max_length = max(ts.shape[1] for ts in encoded_ts_arrays) padded_ts_arrays = [ np.pad(ts, ((0, 0), (0, max_length - ts.shape[1]), (0, 0)), mode="constant", constant_values=0.0) for ts in encoded_ts_arrays ] concatenated_ts = np.concatenate(padded_ts_arrays, axis=0) # Shape: [batch_size, max_length, feature_dim] # Convert to torch concatenated_ts = torch.from_numpy(concatenated_ts).half()
# Tokenize the processed prompt tokenizer_outputs = {} if tokenize and self.tokenizer is not None: tokenizer_outputs = self.tokenizer(reconstructed_prompts, padding=padding, padding_side=padding_side, **kwargs) else: tokenizer_outputs = {"text": reconstructed_prompts}
# Create the final output outputs = tokenizer_outputs if vllm_flag: outputs["timeseries"] = zip(ts_tokens, encoded_ts_arrays) elif concatenated_ts is not None: outputs["timeseries"] = concatenated_ts
return BatchFeature(data=outputs)
def encode_timeseries( self, timeseries: Optional[List[List[np.ndarray]]] = None, ) -> np.ndarray: if timeseries is None: timeseries = []
concatenated_ts = None encoded_ts_arrays = []
for i, ts in enumerate(timeseries): encoded_ts, _, _ = sp_encoding(ts) # Ensure time series shape [1, seq_len, feature_dim] for batch concatenation encoded_ts_arrays.append(encoded_ts[None, ...])
if len(encoded_ts_arrays) > 0: # Pad time series to the same length max_length = max(ts.shape[1] for ts in encoded_ts_arrays) padded_ts_arrays = [ np.pad(ts, ((0, 0), (0, max_length - ts.shape[1]), (0, 0)), mode="constant", constant_values=0.0) for ts in encoded_ts_arrays ] concatenated_ts = np.concatenate(padded_ts_arrays, axis=0) # Shape: [batch_size, max_length, feature_dim] # Convert to torch concatenated_ts = torch.from_numpy(concatenated_ts).half()
return concatenated_ts
@property def model_input_names(self): """ Define the input names expected by the model. """ tokenizer_input_names = [] if self.tokenizer and hasattr(self.tokenizer, "model_input_names"): tokenizer_input_names = self.tokenizer.model_input_names return list(dict.fromkeys(["processed_prompt", "time_series"] + tokenizer_input_names))
def batch_decode(self, *args, **kwargs): """ This method forwards all its arguments to Qwen3TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please refer to the docstring of this method for more information. """ return self.tokenizer.batch_decode(*args, **kwargs)
def decode(self, *args, **kwargs): """ This method forwards all its arguments to Qwen3TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to the docstring of this method for more information. """ return self.tokenizer.decode(*args, **kwargs)chatts/lapras_ecg/added_tokens.jsonAdded+32
chatts/lapras_ecg/chat_template.jinjaAdded+89
chatts/lapras_ecg/config.jsonAdded+90
chatts/lapras_ecg/configuration_qwen3_ts.pyAdded+225
chatts/lapras_ecg/generation_config.jsonAdded+13
chatts/lapras_ecg/lapras_run_config.jsonAdded+12
chatts/lapras_ecg/merges.txtAdded
chatts/lapras_ecg/modeling_qwen3_ts.pyAdded+601
chatts/lapras_ecg/processing_qwen3_ts.pyAdded+224
chatts/lapras_ecg/processor_config.jsonAdded+6
chatts/lapras_ecg/pytorch_model.bin.index.jsonAdded+424
chatts/lapras_ecg/special_tokens_map.jsonAdded+20
chatts/lapras_ecg/tokenizer_config.jsonAdded+265
chatts/lapras_ecg/vocab.jsonAdded
chatts/lapras_engine/added_tokens.jsonAdded+32
chatts/lapras_engine/chat_template.jinjaAdded+89
chatts/lapras_engine/config.jsonAdded+90
chatts/lapras_engine/configuration_qwen3_ts.pyAdded+225
chatts/lapras_engine/generation_config.jsonAdded+13
chatts/lapras_engine/lapras_run_config.jsonAdded+12
chatts/lapras_engine/merges.txtAdded
chatts/lapras_engine/modeling_qwen3_ts.pyAdded+601
chatts/lapras_engine/processing_qwen3_ts.pyAdded+224
chatts/lapras_engine/processor_config.jsonAdded+6
chatts/lapras_engine/pytorch_model.bin.index.jsonAdded+425
chatts/lapras_engine/tokenizer_config.jsonAdded+265
chatts/lapras_engine/vocab.jsonAdded
chatts/lapras_har/added_tokens.jsonAdded+32
chatts/lapras_har/chat_template.jinjaAdded+89
chatts/lapras_har/config.jsonAdded+90
chatts/lapras_har/configuration_qwen3_ts.pyAdded+225
chatts/lapras_har/generation_config.jsonAdded+13
chatts/lapras_har/lapras_run_config.jsonAdded+12
chatts/lapras_har/merges.txtAdded
chatts/lapras_har/modeling_qwen3_ts.pyAdded+601
chatts/lapras_har/processing_qwen3_ts.pyAdded+224
chatts/lapras_har/processor_config.jsonAdded+6
chatts/lapras_har/pytorch_model.bin.index.jsonAdded+425
chatts/lapras_har/special_tokens_map.jsonAdded+20
chatts/lapras_har/tokenizer_config.jsonAdded+265
chatts/lapras_har/vocab.jsonAdded
chatts/lapras_sleep/added_tokens.jsonAdded+32
chatts/lapras_sleep/chat_template.jinjaAdded+89
chatts/lapras_sleep/config.jsonAdded+90
chatts/lapras_sleep/configuration_qwen3_ts.pyAdded+225
chatts/lapras_sleep/generation_config.jsonAdded+13
chatts/lapras_sleep/lapras_run_config.jsonAdded+12
chatts/lapras_sleep/merges.txtAdded
chatts/lapras_sleep/modeling_qwen3_ts.pyAdded+601
chatts/lapras_sleep/processing_qwen3_ts.pyAdded+224