TensorMind commited on
Commit
69262b5
·
verified ·
1 Parent(s): fe2f482

Add files using upload-large-folder tool

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/compare_table_tensormind.png filter=lfs diff=lfs merge=lfs -text
37
+ assets/compare_radar_tensormind.png filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,3 +1,123 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ library_name: transformers
4
+ pipeline_tag: text-generation
5
+ tags:
6
+ - tensormind
7
+ - causal-lm
8
+ - text-generation
9
+ - chinese
10
+ - custom-code
11
+ language:
12
+ - zh
13
+ - en
14
+ model-index:
15
+ - name: TensorMind
16
+ results:
17
+ - task:
18
+ type: text-generation
19
+ name: Chinese Multiple-Choice Evaluation
20
+ dataset:
21
+ type: custom
22
+ name: C-Eval
23
+ metrics:
24
+ - type: accuracy
25
+ value: 27.27
26
+ name: C-Eval (0-shot)
27
+ - task:
28
+ type: text-generation
29
+ name: Chinese Multiple-Choice Evaluation
30
+ dataset:
31
+ type: custom
32
+ name: CMMLU
33
+ metrics:
34
+ - type: accuracy
35
+ value: 25.26
36
+ name: CMMLU (0-shot)
37
+ - task:
38
+ type: text-generation
39
+ name: Chinese Multiple-Choice Evaluation
40
+ dataset:
41
+ type: custom
42
+ name: A-CLUE
43
+ metrics:
44
+ - type: accuracy
45
+ value: 25.43
46
+ name: A-CLUE (0-shot)
47
+ - task:
48
+ type: text-generation
49
+ name: Chinese Multiple-Choice Evaluation
50
+ dataset:
51
+ type: custom
52
+ name: TMMLU+
53
+ metrics:
54
+ - type: accuracy
55
+ value: 24.96
56
+ name: TMMLU+ (0-shot)
57
+ ---
58
+
59
+ # TensorMind (0.5B)
60
+
61
+ TensorMind is a 536.9M-parameter causal language model for lightweight Chinese/English text generation.
62
+
63
+ ## Model Details
64
+
65
+ - Architecture: Decoder-only Transformer (`TensorMindForCausalLM`)
66
+ - Layers: 32
67
+ - Hidden size: 1024
68
+ - Heads / KV heads: 16 / 8 (GQA)
69
+ - Context length: 32,768
70
+ - Vocab size: 32,768
71
+ - Positional encoding: RoPE
72
+ - Activation: SiLU
73
+ - Parameters: 536,941,568 (~0.5B)
74
+
75
+ ## Quick Start
76
+
77
+ ```python
78
+ import torch
79
+ from transformers import AutoTokenizer, AutoModelForCausalLM
80
+
81
+ repo_id = "TensorMind/TensorMind"
82
+ tokenizer = AutoTokenizer.from_pretrained(repo_id, trust_remote_code=True)
83
+ model = AutoModelForCausalLM.from_pretrained(
84
+ repo_id,
85
+ trust_remote_code=True,
86
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
87
+ )
88
+
89
+ prompt = "请用三句话介绍一下你自己。"
90
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
91
+ outputs = model.generate(**inputs, max_new_tokens=128, do_sample=True, temperature=0.7)
92
+ print(tokenizer.decode(outputs[0], skip_special_tokens=True))
93
+ ```
94
+
95
+ ## Benchmark Snapshot
96
+
97
+ Evaluation time: 2026-03-07 00:40 (UTC+8), zero-shot (`n-shot=0`).
98
+
99
+ | Model | Params | C-Eval | CMMLU | A-CLUE | TMMLU+ | AGIEval |
100
+ |---|---:|---:|---:|---:|---:|---:|
101
+ | TensorMind | 0.5B | 27.27 | 25.26 | 25.43 | 24.96 | 33.56 |
102
+
103
+
104
+ ![TensorMind benchmark table](./assets/compare_table_tensormind.png)
105
+
106
+
107
+ ![TensorMind benchmark radar](./assets/compare_radar_tensormind.png)
108
+
109
+ ## Intended Use
110
+
111
+ - Lightweight chat and text generation
112
+ - Local experimentation and teaching
113
+ - Baseline model for research and fine-tuning
114
+
115
+ ## Limitations
116
+
117
+ - This is a small model and can produce factual errors.
118
+ - Benchmark numbers above are from multiple-choice style evaluations and do not fully represent open-ended generation quality.
119
+ - Outputs may contain bias or unsafe content; apply filtering for production use.
120
+
121
+ ## License
122
+
123
+ MIT License.
assets/compare_radar_tensormind.png ADDED

Git LFS Details

  • SHA256: 9541d8dea37ce504869fa0fe42327bbe91dbfb858357ac2899c8521a2562ccfd
  • Pointer size: 131 Bytes
  • Size of remote file: 561 kB
assets/compare_table_tensormind.png ADDED

Git LFS Details

  • SHA256: 334a57f02008c717c0970b7b494c7f28d2bba88610b328e863480b62c7104d7f
  • Pointer size: 131 Bytes
  • Size of remote file: 580 kB
chat_template.jinja ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0].role == 'system' %}
4
+ {{- messages[0].content + '\n\n' }}
5
+ {%- endif %}
6
+ {{- "# Tools"
7
+ "\n\nYou may call one or more functions to assist with the user query."
8
+ "\n\nYou are provided with function signatures within <tools></tools> XML tags:"
9
+ "\n<tools>"
10
+ }}
11
+ {%- for tool in tools %}
12
+ {{- "\n" }}
13
+ {{- tool | tojson }}
14
+ {%- endfor %}
15
+ {{- "\n</tools>"
16
+ "\n\nFor each function call, return a json object with function name "
17
+ "and arguments within <tool_call></tool_call> XML tags:"
18
+ "\n<tool_call>"
19
+ "\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n"
20
+ }}
21
+ {%- else %}
22
+ {%- if messages[0].role == 'system' %}
23
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
24
+ {%- endif %}
25
+ {%- endif %}
26
+ {# record the last query index #}
27
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
28
+ {%- for message in messages[::-1] %}
29
+ {%- set reverse_index = (messages|length - 1) - loop.index0 %}
30
+ {%- if ns.multi_step_tool and message.role == "user" and message.content is string
31
+ and not(message.content.startswith('<tool_response>')
32
+ and message.content.endswith('</tool_response>'))
33
+ %}
34
+ {%- set ns.multi_step_tool = false %}
35
+ {%- set ns.last_query_index = reverse_index %}
36
+ {%- endif %}
37
+ {%- endfor %}
38
+ {%- for message in messages %}
39
+ {%- if message.content is string %}
40
+ {%- set content = message.content %}
41
+ {%- else %}
42
+ {%- set content = '' %}
43
+ {%- endif %}
44
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
45
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
46
+ {%- elif message.role == "assistant" %}
47
+ {%- set reasoning_content = '' %}
48
+ {%- if message.reasoning_content is string %}
49
+ {%- set reasoning_content = message.reasoning_content %}
50
+ {%- else %}
51
+ {%- if '</think>' in content %}
52
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
53
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
54
+ {%- endif %}
55
+ {%- endif %}
56
+ {%- if loop.index0 > ns.last_query_index %}
57
+ {%- if loop.last or reasoning_content %}
58
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
59
+ {%- else %}
60
+ {{- '<|im_start|>' + message.role + '\n' + content }}
61
+ {%- endif %}
62
+ {%- else %}
63
+ {{- '<|im_start|>' + message.role + '\n' + content }}
64
+ {%- endif %}
65
+ {%- if message.tool_calls %}
66
+ {%- for tool_call in message.tool_calls %}
67
+ {%- if content or (not loop.first) %}
68
+ {{- '\n' }}
69
+ {%- endif %}
70
+ {%- if tool_call.function %}
71
+ {%- set tool_call = tool_call.function %}
72
+ {%- endif %}
73
+ {{- '<tool_call>\n{"name": "' }}
74
+ {{- tool_call.name }}
75
+ {{- '", "arguments": ' }}
76
+ {%- if tool_call.arguments is string %}
77
+ {{- tool_call.arguments }}
78
+ {%- else %}
79
+ {{- tool_call.arguments | tojson }}
80
+ {%- endif %}
81
+ {{- '}\n</tool_call>' }}
82
+ {%- endfor %}
83
+ {%- endif %}
84
+ {{- '<|im_end|>\n' }}
85
+ {%- elif message.role == "tool" %}
86
+ {# Short circuiting avoids out-of-bounds #}
87
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
88
+ {{- '<|im_start|>user' }}
89
+ {%- endif %}
90
+ {{- '\n<tool_response>\n' }}
91
+ {{- content }}
92
+ {{- '\n</tool_response>' }}
93
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
94
+ {{- '<|im_end|>\n' }}
95
+ {%- endif %}
96
+ {%- endif %}
97
+ {%- endfor %}
98
+ {%- if add_generation_prompt %}
99
+ {{- '<|im_start|>assistant\n' }}
100
+ {%- if enable_thinking is defined and enable_thinking is false %}
101
+ {{- '<think>\n\n</think>\n\n' }}
102
+ {%- endif %}
103
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "TensorMindForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_tensormind.TensorMindConfig",
9
+ "AutoModel": "modeling_tensormind.TensorMindModel",
10
+ "AutoModelForCausalLM": "modeling_tensormind.TensorMindForCausalLM"
11
+ },
12
+ "bos_token_id": null,
13
+ "dtype": "float32",
14
+ "eos_token_id": null,
15
+ "hidden_act": "silu",
16
+ "hidden_size": 1024,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 4096,
19
+ "max_position_embeddings": 32768,
20
+ "model_type": "tensormind",
21
+ "num_attention_heads": 16,
22
+ "num_hidden_layers": 32,
23
+ "num_key_value_heads": 8,
24
+ "pad_token_id": null,
25
+ "rms_norm_eps": 1e-06,
26
+ "rope_parameters": {
27
+ "rope_theta": 10000.0,
28
+ "rope_type": "default"
29
+ },
30
+ "tie_word_embeddings": true,
31
+ "transformers_version": "5.1.0",
32
+ "use_cache": true,
33
+ "vocab_size": 32768
34
+ }
configuration_tensormind.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The TensorMind team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """TensorMind model configuration"""
15
+
16
+ try:
17
+ from transformers.configuration_utils import PreTrainedConfig
18
+ from transformers.modeling_rope_utils import RopeParameters
19
+ except ImportError:
20
+ from transformers.configuration_utils import PretrainedConfig as PreTrainedConfig
21
+ RopeParameters = None
22
+
23
+
24
+ class TensorMindConfig(PreTrainedConfig):
25
+ model_type = "tensormind"
26
+ keys_to_ignore_at_inference = ["past_key_values"]
27
+ base_model_tp_plan = {
28
+ "layers.*.self_attn.q_proj": "colwise",
29
+ "layers.*.self_attn.k_proj": "colwise",
30
+ "layers.*.self_attn.v_proj": "colwise",
31
+ "layers.*.self_attn.o_proj": "rowwise",
32
+ "layers.*.mlp.gate_proj": "colwise",
33
+ "layers.*.mlp.up_proj": "colwise",
34
+ "layers.*.mlp.down_proj": "rowwise",
35
+ }
36
+ base_model_pp_plan = {
37
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
38
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
39
+ "norm": (["hidden_states"], ["hidden_states"]),
40
+ }
41
+
42
+ def __init__(
43
+ self,
44
+ vocab_size: int | None = 32768,
45
+ hidden_size: int | None = 1024,
46
+ intermediate_size: int | None = 4096,
47
+ num_hidden_layers: int | None = 32,
48
+ num_attention_heads: int | None = 16,
49
+ num_key_value_heads: int | None = 8,
50
+ hidden_act: str | None = "silu",
51
+ max_position_embeddings: int | None = 32768,
52
+ initializer_range: float | None = 0.02,
53
+ rms_norm_eps: int | None = 1e-6,
54
+ use_cache: bool | None = True,
55
+ tie_word_embeddings: bool | None = True,
56
+ attention_bias: bool | None = False,
57
+ attention_dropout: float | None = 0.0,
58
+ pad_token_id: int | None = None,
59
+ bos_token_id: int | None = None,
60
+ eos_token_id: int | None = None,
61
+ rope_parameters: RopeParameters | dict[str, RopeParameters] | None = {
62
+ "rope_type": "default",
63
+ "rope_theta": 10000.0,
64
+ # YaRN
65
+ # "factor": 4.0,
66
+ # "original_max_position_embeddings": 32768,
67
+ # "attention_factor": 1.0,
68
+ # "beta_fast": 32.0,
69
+ # "beta_slow": 1.0,
70
+ },
71
+ **kwargs,
72
+ ):
73
+ self.vocab_size = vocab_size
74
+ self.max_position_embeddings = max_position_embeddings
75
+ self.hidden_size = hidden_size
76
+ self.intermediate_size = intermediate_size
77
+ self.num_hidden_layers = num_hidden_layers
78
+ self.num_attention_heads = num_attention_heads
79
+ self.num_key_value_heads = num_key_value_heads
80
+ self.hidden_act = hidden_act
81
+ self.initializer_range = initializer_range
82
+ self.rms_norm_eps = rms_norm_eps
83
+ self.use_cache = use_cache
84
+ self.attention_bias = attention_bias
85
+ self.attention_dropout = attention_dropout
86
+ self.rope_parameters = rope_parameters
87
+ self.tie_word_embeddings = tie_word_embeddings
88
+ self.pad_token_id = pad_token_id
89
+ self.bos_token_id = bos_token_id
90
+ self.eos_token_id = eos_token_id
91
+
92
+ self._attn_implementation = "sdpa"
93
+ super().__init__(**kwargs)
94
+
95
+
96
+ __all__ = ["TensorMindConfig"]
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0176d6ca0633970b83527713a4242c8b58ca4b5c961eea456f329dca55a17bfe
3
+ size 2147806320
modeling_tensormind.py ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Union, Callable
2
+
3
+ import torch
4
+ from torch import nn
5
+
6
+ from transformers.activations import ACT2FN
7
+ from transformers.cache_utils import Cache, DynamicCache
8
+ from transformers.generation import GenerationMixin
9
+ from transformers.integrations import use_kernel_forward_from_hub
10
+ from transformers.masking_utils import create_causal_mask
11
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
12
+ from transformers.modeling_layers import (
13
+ GenericForQuestionAnswering,
14
+ GenericForSequenceClassification,
15
+ GenericForTokenClassification,
16
+ GradientCheckpointingLayer,
17
+ )
18
+ from transformers.modeling_outputs import CausalLMOutputWithPast, BaseModelOutputWithPast
19
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
20
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
21
+ from transformers.processing_utils import Unpack
22
+ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
23
+ from transformers.utils.generic import check_model_inputs, maybe_autocast
24
+ from .configuration_tensormind import TensorMindConfig
25
+
26
+
27
+ class TensorMindRotaryEmbedding(nn.Module):
28
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
29
+
30
+ def __init__(self, config: TensorMindConfig, device: Optional[torch.device] = None):
31
+ super().__init__()
32
+ self.config = config
33
+ self.max_seq_len_cached = config.max_position_embeddings
34
+ self.original_max_seq_len = config.max_position_embeddings
35
+
36
+ self.rope_type = self.config.rope_parameters["rope_type"]
37
+ rope_init_fn: Callable = self.compute_default_rope_parameters
38
+ if self.rope_type != "default":
39
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
40
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
41
+
42
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
43
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
44
+
45
+ @staticmethod
46
+ def compute_default_rope_parameters(
47
+ config: TensorMindConfig | None = None,
48
+ device: Optional[torch.device] = None
49
+ ) -> tuple[torch.Tensor, float]:
50
+ base = config.rope_parameters["rope_theta"]
51
+ partial_rotary_factor = config.rope_parameters.get("partial_rotary_factor", 1.0)
52
+ head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
53
+ dim = int(head_dim * partial_rotary_factor)
54
+
55
+ attention_factor = 1.0 # Unused in this type of RoPE
56
+
57
+ # Compute the inverse frequencies
58
+ inv_freq = 1.0 / (
59
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
60
+ )
61
+ return inv_freq, attention_factor
62
+
63
+ @torch.no_grad()
64
+ @dynamic_rope_update
65
+ def forward(self, x, position_ids):
66
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
67
+ position_ids_expanded = position_ids[:, None, :].float()
68
+
69
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
70
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
71
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
72
+ emb = torch.cat((freqs, freqs), dim=-1)
73
+ cos = emb.cos() * self.attention_scaling
74
+ sin = emb.sin() * self.attention_scaling
75
+
76
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
77
+
78
+
79
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
80
+ def rotate_half(x):
81
+ x1 = x[..., : x.shape[-1] // 2]
82
+ x2 = x[..., x.shape[-1] // 2 :]
83
+ return torch.cat((-x2, x1), dim=-1)
84
+
85
+ # unsqueeze to match dim
86
+ cos = cos.unsqueeze(unsqueeze_dim)
87
+ sin = sin.unsqueeze(unsqueeze_dim)
88
+
89
+ # Keep half or full tensor for later concatenation
90
+ rotary_dim = cos.shape[-1]
91
+ q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
92
+ k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
93
+
94
+ # Apply rotary embeddings on the first half or full tensor
95
+ q_embed = (q_rot * cos) + (rotate_half(q_rot) * sin)
96
+ k_embed = (k_rot * cos) + (rotate_half(k_rot) * sin)
97
+
98
+ # Concatenate back to full shape
99
+ q_embed = torch.cat([q_embed, q_pass], dim=-1)
100
+ k_embed = torch.cat([k_embed, k_pass], dim=-1)
101
+ return q_embed, k_embed
102
+
103
+
104
+ @use_kernel_forward_from_hub("RMSNorm")
105
+ class TensorMindRMSNorm(nn.Module):
106
+ def __init__(self, hidden_size, eps=1e-6):
107
+ super().__init__()
108
+ self.weight = nn.Parameter(torch.ones(hidden_size))
109
+ self.variance_epsilon = eps
110
+
111
+ def forward(self, hidden_states):
112
+ input_dtype = hidden_states.dtype
113
+ hidden_states = hidden_states.to(torch.float32)
114
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
115
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
116
+ return self.weight * hidden_states.to(input_dtype)
117
+
118
+ def extra_repr(self):
119
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
120
+
121
+
122
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
123
+ """
124
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep).
125
+ The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
126
+ """
127
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
128
+ if n_rep == 1:
129
+ return hidden_states
130
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
131
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
132
+
133
+
134
+ def eager_attention_forward(
135
+ module: nn.Module,
136
+ query: torch.Tensor,
137
+ key: torch.Tensor,
138
+ value: torch.Tensor,
139
+ attention_mask: torch.Tensor | None,
140
+ scaling: float,
141
+ dropout: float = 0.0,
142
+ **kwargs: Unpack[TransformersKwargs],
143
+ ):
144
+ key_states = repeat_kv(key, module.num_key_value_groups)
145
+ value_states = repeat_kv(value, module.num_key_value_groups)
146
+
147
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
148
+ if attention_mask is not None:
149
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
150
+ attn_weights = attn_weights + causal_mask
151
+
152
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
153
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
154
+ attn_output = torch.matmul(attn_weights, value_states)
155
+ attn_output = attn_output.transpose(1, 2).contiguous()
156
+
157
+ return attn_output, attn_weights
158
+
159
+
160
+ class TensorMindAttention(nn.Module):
161
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
162
+
163
+ def __init__(self, config: TensorMindConfig, layer_idx: int):
164
+ super().__init__()
165
+ self.config = config
166
+ self.layer_idx = layer_idx
167
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
168
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
169
+ self.scaling = self.head_dim**-0.5
170
+ self.attention_dropout = config.attention_dropout
171
+ self.is_causal = True
172
+
173
+ self.q_proj = nn.Linear(
174
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
175
+ )
176
+ self.k_proj = nn.Linear(
177
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
178
+ )
179
+ self.v_proj = nn.Linear(
180
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
181
+ )
182
+ self.o_proj = nn.Linear(
183
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
184
+ )
185
+ self.q_norm = TensorMindRMSNorm(self.head_dim, eps=config.rms_norm_eps)
186
+ self.k_norm = TensorMindRMSNorm(self.head_dim, eps=config.rms_norm_eps)
187
+
188
+ def forward(
189
+ self,
190
+ hidden_states: torch.Tensor,
191
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
192
+ attention_mask: torch.Tensor | None,
193
+ past_key_values: Cache | None = None,
194
+ cache_position: torch.LongTensor | None = None,
195
+ **kwargs: Unpack[FlashAttentionKwargs],
196
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
197
+ input_shape = hidden_states.shape[:-1]
198
+ hidden_shape = (*input_shape, -1, self.head_dim)
199
+
200
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
201
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
202
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
203
+
204
+ query_states = self.q_norm(query_states)
205
+ key_states = self.k_norm(key_states)
206
+
207
+ cos, sin = position_embeddings
208
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
209
+
210
+ if past_key_values is not None:
211
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
212
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
213
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
214
+
215
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
216
+ self.config._attn_implementation, eager_attention_forward
217
+ )
218
+
219
+ attn_output, attn_weights = attention_interface(
220
+ self,
221
+ query_states,
222
+ key_states,
223
+ value_states,
224
+ attention_mask,
225
+ dropout=0.0 if not self.training else self.attention_dropout,
226
+ scaling=self.scaling,
227
+ **kwargs,
228
+ )
229
+
230
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
231
+ attn_output = self.o_proj(attn_output)
232
+ return attn_output, attn_weights
233
+
234
+
235
+ @use_kernel_forward_from_hub("SwiGLUMLP")
236
+ class TensorMindMLP(nn.Module):
237
+ def __init__(self, config: TensorMindConfig):
238
+ super().__init__()
239
+ self.config = config
240
+ self.hidden_size = config.hidden_size
241
+ self.intermediate_size = config.intermediate_size
242
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
243
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
244
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
245
+ self.act_fn = ACT2FN[config.hidden_act]
246
+
247
+ def forward(self, x):
248
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
249
+ return down_proj
250
+
251
+
252
+ class TensorMindDecoderLayer(GradientCheckpointingLayer):
253
+ def __init__(self, config: TensorMindConfig, layer_idx: int):
254
+ super().__init__()
255
+ self.self_attn = TensorMindAttention(config, layer_idx)
256
+ self.mlp = TensorMindMLP(config)
257
+ self.input_layernorm = TensorMindRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
258
+ self.post_attention_layernorm = TensorMindRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
259
+
260
+ def forward(
261
+ self,
262
+ hidden_states: torch.Tensor,
263
+ attention_mask: torch.Tensor | None = None,
264
+ position_ids: torch.LongTensor | None = None,
265
+ past_key_values: Cache | None = None,
266
+ use_cache: bool | None = False,
267
+ cache_position: torch.LongTensor | None = None,
268
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
269
+ **kwargs: Unpack[TransformersKwargs],
270
+ ) -> torch.Tensor:
271
+ residual = hidden_states
272
+ hidden_states = self.input_layernorm(hidden_states)
273
+ # Self Attention
274
+ hidden_states, _ = self.self_attn(
275
+ hidden_states=hidden_states,
276
+ attention_mask=attention_mask,
277
+ position_ids=position_ids,
278
+ past_key_values=past_key_values,
279
+ use_cache=use_cache,
280
+ cache_position=cache_position,
281
+ position_embeddings=position_embeddings,
282
+ **kwargs,
283
+ )
284
+ hidden_states = residual + hidden_states
285
+
286
+ # Fully Connected
287
+ residual = hidden_states
288
+ hidden_states = self.post_attention_layernorm(hidden_states)
289
+ hidden_states = self.mlp(hidden_states)
290
+ hidden_states = residual + hidden_states
291
+ return hidden_states
292
+
293
+
294
+ @auto_docstring
295
+ class TensorMindPreTrainedModel(PreTrainedModel):
296
+ config: TensorMindConfig
297
+ base_model_prefix = "model"
298
+ supports_gradient_checkpointing = True
299
+ _no_split_modules = ["TensorMindDecoderLayer"]
300
+ _skip_keys_device_placement = ["past_key_values"]
301
+ _supports_flash_attn = True
302
+ _supports_sdpa = True
303
+ _supports_flex_attn = True
304
+
305
+ _can_compile_fullgraph = True
306
+ _supports_attention_backend = True
307
+ _can_record_outputs = {
308
+ "hidden_states": TensorMindDecoderLayer,
309
+ "attentions": TensorMindAttention,
310
+ }
311
+
312
+
313
+ @auto_docstring
314
+ class TensorMindModel(TensorMindPreTrainedModel):
315
+ def __init__(self, config: TensorMindConfig):
316
+ super().__init__(config)
317
+ self.padding_idx = config.pad_token_id
318
+ self.vocab_size = config.vocab_size
319
+
320
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
321
+ self.layers = nn.ModuleList(
322
+ [TensorMindDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
323
+ )
324
+ self.norm = TensorMindRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
325
+ self.rotary_emb = TensorMindRotaryEmbedding(config=config)
326
+ self.gradient_checkpointing = False
327
+
328
+ # Initialize weights and apply final processing
329
+ self.post_init()
330
+
331
+ @check_model_inputs
332
+ @auto_docstring
333
+ def forward(
334
+ self,
335
+ input_ids: Optional[torch.LongTensor] = None,
336
+ attention_mask: Optional[torch.Tensor] = None,
337
+ position_ids: Optional[torch.LongTensor] = None,
338
+ past_key_values: Optional[Cache] = None,
339
+ inputs_embeds: Optional[torch.FloatTensor] = None,
340
+ use_cache: Optional[bool] = None,
341
+ cache_position: Optional[torch.LongTensor] = None,
342
+ **kwargs: Unpack[TransformersKwargs],
343
+ ) -> BaseModelOutputWithPast:
344
+ if (input_ids is None) ^ (inputs_embeds is not None):
345
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
346
+
347
+ if use_cache and past_key_values is None:
348
+ past_key_values = DynamicCache(config=self.config)
349
+
350
+ if inputs_embeds is None:
351
+ inputs_embeds = self.embed_tokens(input_ids)
352
+
353
+ if cache_position is None:
354
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
355
+ cache_position: torch.Tensor = (
356
+ torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
357
+ )
358
+
359
+ if position_ids is None:
360
+ position_ids = cache_position.unsqueeze(0)
361
+
362
+ causal_mask = create_causal_mask(
363
+ config=self.config,
364
+ input_embeds=inputs_embeds,
365
+ attention_mask=attention_mask,
366
+ cache_position=cache_position,
367
+ past_key_values=past_key_values,
368
+ position_ids=position_ids,
369
+ )
370
+
371
+ hidden_states = inputs_embeds
372
+ position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
373
+
374
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
375
+ hidden_states = decoder_layer(
376
+ hidden_states,
377
+ attention_mask=causal_mask,
378
+ position_ids=position_ids,
379
+ past_key_values=past_key_values,
380
+ use_cache=use_cache,
381
+ cache_position=cache_position,
382
+ position_embeddings=position_embeddings,
383
+ **kwargs,
384
+ )
385
+
386
+ hidden_states = self.norm(hidden_states)
387
+
388
+ return BaseModelOutputWithPast(
389
+ last_hidden_state=hidden_states,
390
+ past_key_values=past_key_values,
391
+ )
392
+
393
+
394
+ @auto_docstring
395
+ class TensorMindForCausalLM(TensorMindPreTrainedModel, GenerationMixin):
396
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
397
+ _tp_plan = {"lm_head": "colwise_gather_output"}
398
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
399
+
400
+ def __init__(self, config: TensorMindConfig):
401
+ super().__init__(config)
402
+ self.model = TensorMindModel(config)
403
+ self.vocab_size = config.vocab_size
404
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
405
+
406
+ # Initialize weights and apply final processing
407
+ self.post_init()
408
+
409
+ @can_return_tuple
410
+ @auto_docstring
411
+ def forward(
412
+ self,
413
+ input_ids: Optional[torch.LongTensor] = None,
414
+ attention_mask: Optional[torch.Tensor] = None,
415
+ position_ids: Optional[torch.LongTensor] = None,
416
+ past_key_values: Optional[Cache] = None,
417
+ inputs_embeds: Optional[torch.FloatTensor] = None,
418
+ labels: Optional[torch.LongTensor] = None,
419
+ use_cache: Optional[bool] = None,
420
+ output_router_logits: Optional[bool] = None,
421
+ cache_position: Optional[torch.LongTensor] = None,
422
+ logits_to_keep: Union[int, torch.Tensor] = 0,
423
+ **kwargs: Unpack[TransformersKwargs],
424
+ ) -> CausalLMOutputWithPast:
425
+
426
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
427
+ outputs: BaseModelOutputWithPast = self.model(
428
+ input_ids=input_ids,
429
+ attention_mask=attention_mask,
430
+ position_ids=position_ids,
431
+ past_key_values=past_key_values,
432
+ inputs_embeds=inputs_embeds,
433
+ use_cache=use_cache,
434
+ output_router_logits=output_router_logits,
435
+ cache_position=cache_position,
436
+ **kwargs,
437
+ )
438
+
439
+ hidden_states = outputs.last_hidden_state
440
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
441
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
442
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
443
+
444
+ loss = None
445
+ if labels is not None:
446
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
447
+
448
+ return CausalLMOutputWithPast(
449
+ loss=loss,
450
+ logits=logits,
451
+ past_key_values=outputs.past_key_values,
452
+ hidden_states=outputs.hidden_states,
453
+ attentions=outputs.attentions,
454
+ )
455
+
456
+
457
+ class TensorMindForSequenceClassification(GenericForSequenceClassification, TensorMindPreTrainedModel):
458
+ pass
459
+
460
+
461
+ class TensorMindForTokenClassification(GenericForTokenClassification, TensorMindPreTrainedModel):
462
+ pass
463
+
464
+
465
+ class TensorMindForQuestionAnswering(GenericForQuestionAnswering, TensorMindPreTrainedModel):
466
+ base_model_prefix = "transformer"
467
+
468
+
469
+ __all__ = [
470
+ "TensorMindModel",
471
+ "TensorMindForCausalLM",
472
+ "TensorMindPreTrainedModel",
473
+ "TensorMindForQuestionAnswering",
474
+ "TensorMindForTokenClassification",
475
+ "TensorMindForSequenceClassification",
476
+ ]
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "backend": "tokenizers",
4
+ "bos_token": "<|im_start|>",
5
+ "clean_up_tokenization_spaces": false,
6
+ "eos_token": "<|im_end|>",
7
+ "errors": "replace",
8
+ "extra_special_tokens": {},
9
+ "is_local": true,
10
+ "model_max_length": 32768,
11
+ "pad_token": "<|endoftext|>",
12
+ "split_special_tokens": false,
13
+ "tokenizer_class": "PreTrainedTokenizerFast",
14
+ "unk_token": null
15
+ }