Commit
·
e1db6ad
verified
·
0
Parent(s):
Duplicate from Abhaykoul/hai3.1-pretrained_final
Browse files- .gitattributes +36 -0
- README.md +5 -0
- added_tokens.json +28 -0
- chat_template.jinja +104 -0
- config.json +86 -0
- configuration_helpingai.py +269 -0
- generation_config.json +13 -0
- merges.txt +0 -0
- model-00001-of-00007.safetensors +3 -0
- model-00002-of-00007.safetensors +3 -0
- model-00003-of-00007.safetensors +3 -0
- model-00004-of-00007.safetensors +3 -0
- model-00005-of-00007.safetensors +3 -0
- model-00006-of-00007.safetensors +3 -0
- model-00007-of-00007.safetensors +3 -0
- model.safetensors.index.json +0 -0
- modeling_helpingai.py +969 -0
- special_tokens_map.json +31 -0
- tokenizer.json +3 -0
- tokenizer_config.json +240 -0
- vocab.json +0 -0
.gitattributes
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
+
*.xz 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 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
license: apache-2.0
|
3 |
+
pipeline_tag: text-generation
|
4 |
+
library_name: transformers
|
5 |
+
---
|
added_tokens.json
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"</think>": 151668,
|
3 |
+
"</tool_call>": 151658,
|
4 |
+
"</tool_response>": 151666,
|
5 |
+
"<think>": 151667,
|
6 |
+
"<tool_call>": 151657,
|
7 |
+
"<tool_response>": 151665,
|
8 |
+
"<|box_end|>": 151649,
|
9 |
+
"<|box_start|>": 151648,
|
10 |
+
"<|endoftext|>": 151643,
|
11 |
+
"<|file_sep|>": 151664,
|
12 |
+
"<|fim_middle|>": 151660,
|
13 |
+
"<|fim_pad|>": 151662,
|
14 |
+
"<|fim_prefix|>": 151659,
|
15 |
+
"<|fim_suffix|>": 151661,
|
16 |
+
"<|im_end|>": 151645,
|
17 |
+
"<|im_start|>": 151644,
|
18 |
+
"<|image_pad|>": 151655,
|
19 |
+
"<|object_ref_end|>": 151647,
|
20 |
+
"<|object_ref_start|>": 151646,
|
21 |
+
"<|quad_end|>": 151651,
|
22 |
+
"<|quad_start|>": 151650,
|
23 |
+
"<|repo_name|>": 151663,
|
24 |
+
"<|video_pad|>": 151656,
|
25 |
+
"<|vision_end|>": 151653,
|
26 |
+
"<|vision_pad|>": 151654,
|
27 |
+
"<|vision_start|>": 151652
|
28 |
+
}
|
chat_template.jinja
ADDED
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{%- set model_identity = "You are HelpingAI 3.1, the most emotionally intelligent and human-like AI model created by HelpingAI. Knowledge cutoff: 2024-01\nCurrent date: " + strftime_now("%Y-%m-%d") + "\n" %}
|
2 |
+
{%- if tools %}
|
3 |
+
{{- '<|im_start|>system\n' }}
|
4 |
+
{{- model_identity }}
|
5 |
+
{%- if messages[0].role == 'system' %}
|
6 |
+
{{- messages[0].content + '\n\n' }}
|
7 |
+
{%- endif %}
|
8 |
+
{{- "# 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>" }}
|
9 |
+
{%- for tool in tools %}
|
10 |
+
{{- "\n" }}
|
11 |
+
{{- tool | tojson }}
|
12 |
+
{%- endfor %}
|
13 |
+
{{- "\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" }}
|
14 |
+
{%- else %}
|
15 |
+
{{- '<|im_start|>system\n' + model_identity }}
|
16 |
+
{%- if messages[0].role == 'system' %}
|
17 |
+
{{- messages[0].content + '<|im_end|>\n' }}
|
18 |
+
{%- else %}
|
19 |
+
{{- '<|im_end|>\n' }}
|
20 |
+
{%- endif %}
|
21 |
+
{%- endif %}
|
22 |
+
{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
|
23 |
+
{%- set last_tool_call = namespace(name=none) %}
|
24 |
+
{%- set ns_assistant = namespace(open=false) %}
|
25 |
+
{%- for forward_message in messages %}
|
26 |
+
{%- set index = (messages|length - 1) - loop.index0 %}
|
27 |
+
{%- set message = messages[index] %}
|
28 |
+
{%- set current_content = message.content if message.content is not none else '' %}
|
29 |
+
{%- set tool_start = '<tool_response>' %}
|
30 |
+
{%- set tool_start_length = tool_start|length %}
|
31 |
+
{%- set start_of_message = current_content[:tool_start_length] %}
|
32 |
+
{%- set tool_end = '</tool_response>' %}
|
33 |
+
{%- set tool_end_length = tool_end|length %}
|
34 |
+
{%- set start_pos = (current_content|length) - tool_end_length %}
|
35 |
+
{%- if start_pos < 0 %}
|
36 |
+
{%- set start_pos = 0 %}
|
37 |
+
{%- endif %}
|
38 |
+
{%- set end_of_message = current_content[start_pos:] %}
|
39 |
+
{%- if ns.multi_step_tool and message.role == "user" and not(start_of_message == tool_start and end_of_message == tool_end) %}
|
40 |
+
{%- set ns.multi_step_tool = false %}
|
41 |
+
{%- set ns.last_query_index = index %}
|
42 |
+
{%- endif %}
|
43 |
+
{%- endfor %}
|
44 |
+
{%- for message in messages %}
|
45 |
+
{%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
|
46 |
+
{%- if ns_assistant.open %}
|
47 |
+
{{- '<|im_end|>\n' }}
|
48 |
+
{%- set ns_assistant.open = false %}
|
49 |
+
{%- endif %}
|
50 |
+
{{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }}
|
51 |
+
{%- elif message.role == "assistant" %}
|
52 |
+
{%- if not ns_assistant.open %}
|
53 |
+
{{- '<|im_start|>assistant\n' }}
|
54 |
+
{%- set ns_assistant.open = true %}
|
55 |
+
{%- endif %}
|
56 |
+
{%- if message.content %}
|
57 |
+
{{- message.content }}
|
58 |
+
{%- endif %}
|
59 |
+
{%- if message.tool_calls %}
|
60 |
+
{%- for tool_call in message.tool_calls %}
|
61 |
+
{%- if (loop.first and content) or (not loop.first) %}
|
62 |
+
{{- '\n' }}
|
63 |
+
{%- endif %}
|
64 |
+
{%- if tool_call.function %}
|
65 |
+
{%- set tool_call = tool_call.function %}
|
66 |
+
{%- endif %}
|
67 |
+
{{- '<tool_call>\n{"name": "' }}
|
68 |
+
{{- tool_call.name }}
|
69 |
+
{{- '", "arguments": ' }}
|
70 |
+
{%- if tool_call.arguments is string %}
|
71 |
+
{{- tool_call.arguments }}
|
72 |
+
{%- else %}
|
73 |
+
{{- tool_call.arguments | tojson }}
|
74 |
+
{%- endif %}
|
75 |
+
{{- '}\n</tool_call>' }}
|
76 |
+
{%- set last_tool_call.name = tool_call.name %}
|
77 |
+
{%- endfor %}
|
78 |
+
{%- else %}
|
79 |
+
{%- set last_tool_call.name = none %}
|
80 |
+
{%- endif %}
|
81 |
+
{%- if loop.last or (messages[loop.index0 + 1].role not in ["assistant", "tool"]) %}
|
82 |
+
{{- '<|im_end|>\n' }}
|
83 |
+
{%- set ns_assistant.open = false %}
|
84 |
+
{%- endif %}
|
85 |
+
{%- elif message.role == "tool" %}
|
86 |
+
{%- if last_tool_call.name is none %}
|
87 |
+
{{- raise_exception("Message has tool role, but there was no previous assistant message with a tool call!") }}
|
88 |
+
{%- endif %}
|
89 |
+
{%- if not ns_assistant.open %}
|
90 |
+
{{- '<|im_start|>assistant\n' }}
|
91 |
+
{%- set ns_assistant.open = true %}
|
92 |
+
{%- endif %}
|
93 |
+
{{- '\n<tool_response>\n' }}
|
94 |
+
{{- message.content }}
|
95 |
+
{{- '\n</tool_response>' }}
|
96 |
+
{%- if loop.last or (messages[loop.index0 + 1].role not in ["assistant", "tool"]) %}
|
97 |
+
{{- '<|im_end|>\n' }}
|
98 |
+
{%- set ns_assistant.open = false %}
|
99 |
+
{%- endif %}
|
100 |
+
{%- endif %}
|
101 |
+
{%- endfor %}
|
102 |
+
{%- if add_generation_prompt %}
|
103 |
+
{{- '<|im_start|>assistant\n' }}
|
104 |
+
{%- endif %}
|
config.json
ADDED
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"HelpingAIForCausalLM"
|
4 |
+
],
|
5 |
+
"attention_bias": false,
|
6 |
+
"attention_dropout": 0.0,
|
7 |
+
"auto_map": {
|
8 |
+
"AutoConfig": "configuration_helpingai.HelpingAIConfig",
|
9 |
+
"AutoModelForCausalLM": "modeling_helpingai.HelpingAIForCausalLM"
|
10 |
+
},
|
11 |
+
"bos_token_id": 151643,
|
12 |
+
"emotion_hidden_size": 512,
|
13 |
+
"empathy_scaling_factor": 1.2,
|
14 |
+
"eos_token_id": 151645,
|
15 |
+
"head_dim": 128,
|
16 |
+
"hidden_act": "silu",
|
17 |
+
"hidden_size": 5120,
|
18 |
+
"initializer_range": 0.02,
|
19 |
+
"intermediate_size": 17408,
|
20 |
+
"layer_types": [
|
21 |
+
"full_attention",
|
22 |
+
"full_attention",
|
23 |
+
"full_attention",
|
24 |
+
"full_attention",
|
25 |
+
"full_attention",
|
26 |
+
"full_attention",
|
27 |
+
"full_attention",
|
28 |
+
"full_attention",
|
29 |
+
"full_attention",
|
30 |
+
"full_attention",
|
31 |
+
"full_attention",
|
32 |
+
"full_attention",
|
33 |
+
"full_attention",
|
34 |
+
"full_attention",
|
35 |
+
"full_attention",
|
36 |
+
"full_attention",
|
37 |
+
"full_attention",
|
38 |
+
"full_attention",
|
39 |
+
"full_attention",
|
40 |
+
"full_attention",
|
41 |
+
"full_attention",
|
42 |
+
"full_attention",
|
43 |
+
"full_attention",
|
44 |
+
"full_attention",
|
45 |
+
"full_attention",
|
46 |
+
"full_attention",
|
47 |
+
"full_attention",
|
48 |
+
"full_attention",
|
49 |
+
"full_attention",
|
50 |
+
"full_attention",
|
51 |
+
"full_attention",
|
52 |
+
"full_attention",
|
53 |
+
"full_attention",
|
54 |
+
"full_attention",
|
55 |
+
"full_attention",
|
56 |
+
"full_attention",
|
57 |
+
"full_attention",
|
58 |
+
"full_attention",
|
59 |
+
"full_attention",
|
60 |
+
"full_attention"
|
61 |
+
],
|
62 |
+
"max_position_embeddings": 40960,
|
63 |
+
"max_window_layers": 40,
|
64 |
+
"model_type": "helpingai",
|
65 |
+
"num_attention_heads": 40,
|
66 |
+
"num_emotion_heads": 4,
|
67 |
+
"num_hidden_layers": 40,
|
68 |
+
"num_key_value_heads": 8,
|
69 |
+
"num_thinking_stages": 3,
|
70 |
+
"perspective_threads": 4,
|
71 |
+
"reasoning_temperature": 0.8,
|
72 |
+
"rms_norm_eps": 1e-06,
|
73 |
+
"rope_scaling": null,
|
74 |
+
"rope_theta": 1000000,
|
75 |
+
"sliding_window": null,
|
76 |
+
"structured_output_vocab_size": 100,
|
77 |
+
"thinking_depth": 2,
|
78 |
+
"tie_word_embeddings": false,
|
79 |
+
"torch_dtype": "bfloat16",
|
80 |
+
"transformers_version": "4.55.0",
|
81 |
+
"use_cache": true,
|
82 |
+
"use_emotional_reasoning": false,
|
83 |
+
"use_perspective_threading": true,
|
84 |
+
"use_sliding_window": false,
|
85 |
+
"vocab_size": 151669
|
86 |
+
}
|
configuration_helpingai.py
ADDED
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""HelpingAI model configuration"""
|
2 |
+
|
3 |
+
from transformers.configuration_utils import PretrainedConfig, layer_type_validation
|
4 |
+
from transformers.modeling_rope_utils import rope_config_validation
|
5 |
+
from transformers.utils import logging
|
6 |
+
|
7 |
+
|
8 |
+
logger = logging.get_logger(__name__)
|
9 |
+
|
10 |
+
|
11 |
+
class HelpingAIConfig(PretrainedConfig):
|
12 |
+
r"""
|
13 |
+
This is the configuration class to store the configuration of a [`HelpingAIModel`]. It is used to instantiate a
|
14 |
+
HelpingAI model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
15 |
+
with the defaults will yield a similar configuration to that of
|
16 |
+
HelpingAI-8B [HelpingAI/HelpingAI-8B](https://huggingface.co/HelpingAI/HelpingAI-8B).
|
17 |
+
|
18 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
19 |
+
documentation from [`PretrainedConfig`] for more information.
|
20 |
+
|
21 |
+
|
22 |
+
Args:
|
23 |
+
vocab_size (`int`, *optional*, defaults to 151936):
|
24 |
+
Vocabulary size of the HelpingAI model. Defines the number of different tokens that can be represented by the
|
25 |
+
`inputs_ids` passed when calling [`HelpingAIModel`]
|
26 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
27 |
+
Dimension of the hidden representations.
|
28 |
+
intermediate_size (`int`, *optional*, defaults to 22016):
|
29 |
+
Dimension of the MLP representations.
|
30 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
31 |
+
Number of hidden layers in the Transformer encoder.
|
32 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
33 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
34 |
+
num_key_value_heads (`int`, *optional*, defaults to 32):
|
35 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
36 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
37 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
38 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
39 |
+
by meanpooling all the original heads within that group. For more details, check out [this
|
40 |
+
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
|
41 |
+
head_dim (`int`, *optional*, defaults to 128):
|
42 |
+
The attention head dimension.
|
43 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
44 |
+
The non-linear activation function (function or string) in the decoder.
|
45 |
+
max_position_embeddings (`int`, *optional*, defaults to 32768):
|
46 |
+
The maximum sequence length that this model might ever be used with.
|
47 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
48 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
49 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
50 |
+
The epsilon used by the rms normalization layers.
|
51 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
52 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
53 |
+
relevant if `config.is_decoder=True`.
|
54 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
55 |
+
Whether the model's input and output word embeddings should be tied.
|
56 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
57 |
+
The base period of the RoPE embeddings.
|
58 |
+
rope_scaling (`Dict`, *optional*):
|
59 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
|
60 |
+
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
|
61 |
+
accordingly.
|
62 |
+
Expected contents:
|
63 |
+
`rope_type` (`str`):
|
64 |
+
The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
|
65 |
+
'llama3'], with 'default' being the original RoPE implementation.
|
66 |
+
`factor` (`float`, *optional*):
|
67 |
+
Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
|
68 |
+
most scaling types, a `factor` of x will enable the model to handle sequences of length x *
|
69 |
+
original maximum pre-trained length.
|
70 |
+
`original_max_position_embeddings` (`int`, *optional*):
|
71 |
+
Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
|
72 |
+
pretraining.
|
73 |
+
`attention_factor` (`float`, *optional*):
|
74 |
+
Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
|
75 |
+
computation. If unspecified, it defaults to value recommended by the implementation, using the
|
76 |
+
`factor` field to infer the suggested value.
|
77 |
+
`beta_fast` (`float`, *optional*):
|
78 |
+
Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
|
79 |
+
ramp function. If unspecified, it defaults to 32.
|
80 |
+
`beta_slow` (`float`, *optional*):
|
81 |
+
Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
|
82 |
+
ramp function. If unspecified, it defaults to 1.
|
83 |
+
`short_factor` (`list[float]`, *optional*):
|
84 |
+
Only used with 'longrope'. The scaling factor to be applied to short contexts (<
|
85 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
86 |
+
size divided by the number of attention heads divided by 2
|
87 |
+
`long_factor` (`list[float]`, *optional*):
|
88 |
+
Only used with 'longrope'. The scaling factor to be applied to long contexts (<
|
89 |
+
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
|
90 |
+
size divided by the number of attention heads divided by 2
|
91 |
+
`low_freq_factor` (`float`, *optional*):
|
92 |
+
Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
|
93 |
+
`high_freq_factor` (`float`, *optional*):
|
94 |
+
Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
|
95 |
+
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
|
96 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
97 |
+
use_sliding_window (`bool`, *optional*, defaults to `False`):
|
98 |
+
Whether to use sliding window attention.
|
99 |
+
sliding_window (`int`, *optional*, defaults to 4096):
|
100 |
+
Sliding window attention (SWA) window size. If not specified, will default to `4096`.
|
101 |
+
max_window_layers (`int`, *optional*, defaults to 28):
|
102 |
+
The number of layers using full attention. The first `max_window_layers` layers will use full attention, while any
|
103 |
+
additional layer afterwards will use SWA (Sliding Window Attention).
|
104 |
+
layer_types (`list`, *optional*):
|
105 |
+
Attention pattern for each layer.
|
106 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
107 |
+
The dropout ratio for the attention probabilities.
|
108 |
+
use_emotional_reasoning (`bool`, *optional*, defaults to `True`):
|
109 |
+
Whether to enable Semantic Emotion Reasoning (SER) capabilities for emotional understanding and processing.
|
110 |
+
use_perspective_threading (`bool`, *optional*, defaults to `True`):
|
111 |
+
Whether to enable Perspective Emotion Threading (PET) for multi-threaded emotional reasoning.
|
112 |
+
num_emotion_heads (`int`, *optional*, defaults to 4):
|
113 |
+
Number of specialized attention heads dedicated to emotional processing and reasoning.
|
114 |
+
num_thinking_stages (`int`, *optional*, defaults to 3):
|
115 |
+
Number of thinking stages for multi-stage reasoning and reflection processing.
|
116 |
+
emotion_hidden_size (`int`, *optional*, defaults to 512):
|
117 |
+
Hidden size for the emotional reasoning layers and SER processing modules.
|
118 |
+
perspective_threads (`int`, *optional*, defaults to 4):
|
119 |
+
Number of parallel perspective threads for PET processing (relatable, supportive, motivational, analytical).
|
120 |
+
thinking_depth (`int`, *optional*, defaults to 2):
|
121 |
+
Depth of thinking layers for internal reasoning and reflection processes.
|
122 |
+
structured_output_vocab_size (`int`, *optional*, defaults to 100):
|
123 |
+
Additional vocabulary size for structured output tokens like <think>, <ser>, <pet>, etc.
|
124 |
+
empathy_scaling_factor (`float`, *optional*, defaults to 1.2):
|
125 |
+
Scaling factor for empathy-related attention weights and emotional processing.
|
126 |
+
reasoning_temperature (`float`, *optional*, defaults to 0.8):
|
127 |
+
Temperature parameter for reasoning and thinking processes to balance creativity and coherence.
|
128 |
+
|
129 |
+
```python
|
130 |
+
>>> from transformers import HelpingAIModel, HelpingAIConfig
|
131 |
+
|
132 |
+
>>> # Initializing a HelpingAI style configuration with advanced reasoning
|
133 |
+
>>> configuration = HelpingAIConfig(
|
134 |
+
... use_emotional_reasoning=True,
|
135 |
+
... use_perspective_threading=True,
|
136 |
+
... num_emotion_heads=4,
|
137 |
+
... num_thinking_stages=3
|
138 |
+
... )
|
139 |
+
|
140 |
+
>>> # Initializing a model from the HelpingAI-8B style configuration
|
141 |
+
>>> model = HelpingAIModel(configuration)
|
142 |
+
|
143 |
+
>>> # Accessing the model configuration
|
144 |
+
>>> configuration = model.config
|
145 |
+
```"""
|
146 |
+
|
147 |
+
model_type = "helpingai"
|
148 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
149 |
+
|
150 |
+
# Default tensor parallel plan for base model `HelpingAI`
|
151 |
+
base_model_tp_plan = {
|
152 |
+
"layers.*.self_attn.q_proj": "colwise",
|
153 |
+
"layers.*.self_attn.k_proj": "colwise",
|
154 |
+
"layers.*.self_attn.v_proj": "colwise",
|
155 |
+
"layers.*.self_attn.o_proj": "rowwise",
|
156 |
+
"layers.*.mlp.gate_proj": "colwise",
|
157 |
+
"layers.*.mlp.up_proj": "colwise",
|
158 |
+
"layers.*.mlp.down_proj": "rowwise",
|
159 |
+
}
|
160 |
+
base_model_pp_plan = {
|
161 |
+
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
|
162 |
+
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
|
163 |
+
"norm": (["hidden_states"], ["hidden_states"]),
|
164 |
+
}
|
165 |
+
|
166 |
+
def __init__(
|
167 |
+
self,
|
168 |
+
vocab_size=151936,
|
169 |
+
hidden_size=4096,
|
170 |
+
intermediate_size=22016,
|
171 |
+
num_hidden_layers=32,
|
172 |
+
num_attention_heads=32,
|
173 |
+
num_key_value_heads=8, # Match num_attention_heads for compatibility
|
174 |
+
head_dim=128,
|
175 |
+
hidden_act="silu",
|
176 |
+
max_position_embeddings=32768,
|
177 |
+
initializer_range=0.02,
|
178 |
+
rms_norm_eps=1e-6,
|
179 |
+
use_cache=True,
|
180 |
+
tie_word_embeddings=False,
|
181 |
+
rope_theta=10000.0,
|
182 |
+
rope_scaling=None,
|
183 |
+
attention_bias=False,
|
184 |
+
use_sliding_window=False,
|
185 |
+
sliding_window=4096,
|
186 |
+
max_window_layers=28,
|
187 |
+
layer_types=None,
|
188 |
+
attention_dropout=0.0,
|
189 |
+
# Advanced reasoning parameters
|
190 |
+
use_emotional_reasoning=False, # Disable by default for now
|
191 |
+
use_perspective_threading=True,
|
192 |
+
num_emotion_heads=4,
|
193 |
+
num_thinking_stages=3,
|
194 |
+
emotion_hidden_size=512,
|
195 |
+
perspective_threads=4,
|
196 |
+
thinking_depth=2,
|
197 |
+
structured_output_vocab_size=100,
|
198 |
+
empathy_scaling_factor=1.2,
|
199 |
+
reasoning_temperature=0.8,
|
200 |
+
**kwargs,
|
201 |
+
):
|
202 |
+
self.vocab_size = vocab_size
|
203 |
+
self.max_position_embeddings = max_position_embeddings
|
204 |
+
self.hidden_size = hidden_size
|
205 |
+
self.intermediate_size = intermediate_size
|
206 |
+
self.num_hidden_layers = num_hidden_layers
|
207 |
+
self.num_attention_heads = num_attention_heads
|
208 |
+
self.use_sliding_window = use_sliding_window
|
209 |
+
self.sliding_window = sliding_window if self.use_sliding_window else None
|
210 |
+
self.max_window_layers = max_window_layers
|
211 |
+
|
212 |
+
# for backward compatibility
|
213 |
+
if num_key_value_heads is None:
|
214 |
+
num_key_value_heads = num_attention_heads
|
215 |
+
|
216 |
+
self.num_key_value_heads = num_key_value_heads
|
217 |
+
self.head_dim = head_dim
|
218 |
+
self.hidden_act = hidden_act
|
219 |
+
self.initializer_range = initializer_range
|
220 |
+
self.rms_norm_eps = rms_norm_eps
|
221 |
+
self.use_cache = use_cache
|
222 |
+
self.rope_theta = rope_theta
|
223 |
+
self.rope_scaling = rope_scaling
|
224 |
+
self.attention_bias = attention_bias
|
225 |
+
self.attention_dropout = attention_dropout
|
226 |
+
|
227 |
+
# Advanced reasoning capabilities
|
228 |
+
self.use_emotional_reasoning = use_emotional_reasoning
|
229 |
+
self.use_perspective_threading = use_perspective_threading
|
230 |
+
self.num_emotion_heads = num_emotion_heads
|
231 |
+
self.num_thinking_stages = num_thinking_stages
|
232 |
+
self.emotion_hidden_size = emotion_hidden_size
|
233 |
+
self.perspective_threads = perspective_threads
|
234 |
+
self.thinking_depth = thinking_depth
|
235 |
+
self.structured_output_vocab_size = structured_output_vocab_size
|
236 |
+
self.empathy_scaling_factor = empathy_scaling_factor
|
237 |
+
self.reasoning_temperature = reasoning_temperature
|
238 |
+
|
239 |
+
# Validate emotional reasoning parameters
|
240 |
+
if self.use_emotional_reasoning and self.num_emotion_heads > self.num_attention_heads:
|
241 |
+
raise ValueError(f"num_emotion_heads ({self.num_emotion_heads}) cannot exceed num_attention_heads ({self.num_attention_heads})")
|
242 |
+
|
243 |
+
if self.use_perspective_threading and self.perspective_threads < 2:
|
244 |
+
raise ValueError(f"perspective_threads ({self.perspective_threads}) must be at least 2 for meaningful threading")
|
245 |
+
|
246 |
+
# Validate the correctness of rotary position embeddings parameters
|
247 |
+
# BC: if there is a 'type' field, move it to 'rope_type'.
|
248 |
+
if self.rope_scaling is not None and "type" in self.rope_scaling:
|
249 |
+
self.rope_scaling["rope_type"] = self.rope_scaling["type"]
|
250 |
+
rope_config_validation(self)
|
251 |
+
|
252 |
+
self.layer_types = layer_types
|
253 |
+
if self.layer_types is None:
|
254 |
+
self.layer_types = [
|
255 |
+
"sliding_attention"
|
256 |
+
if self.sliding_window is not None and i >= self.max_window_layers
|
257 |
+
else "full_attention"
|
258 |
+
for i in range(self.num_hidden_layers)
|
259 |
+
]
|
260 |
+
layer_type_validation(self.layer_types)
|
261 |
+
|
262 |
+
super().__init__(
|
263 |
+
tie_word_embeddings=tie_word_embeddings,
|
264 |
+
**kwargs,
|
265 |
+
)
|
266 |
+
|
267 |
+
|
268 |
+
__all__ = ["HelpingAIConfig"]
|
269 |
+
|
generation_config.json
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token_id": 151643,
|
3 |
+
"do_sample": true,
|
4 |
+
"eos_token_id": [
|
5 |
+
151645,
|
6 |
+
151643
|
7 |
+
],
|
8 |
+
"pad_token_id": 151643,
|
9 |
+
"temperature": 0.6,
|
10 |
+
"top_k": 20,
|
11 |
+
"top_p": 0.95,
|
12 |
+
"transformers_version": "4.55.0"
|
13 |
+
}
|
merges.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
model-00001-of-00007.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:cd0e66019b5ea698d577625397f8bd4e0e90b054b2f0d84c3d9af018d5cd34e4
|
3 |
+
size 4887893216
|
model-00002-of-00007.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:932087a0b7283cc26967d9821b932a85a4f3b721af8d729b4c7c7c112411134d
|
3 |
+
size 4991798206
|
model-00003-of-00007.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d97f54b342f1bf9c4cd5c8facef8f6f7db5608404d92bf28f2ccc4cca24026d3
|
3 |
+
size 4991798414
|
model-00004-of-00007.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1d0f940b8973cb5a2f9e6a3db0fde2d251245a252321d7f7f65e263ba8742822
|
3 |
+
size 4991798414
|
model-00005-of-00007.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:2bec76fc8084bf6d11e2d425bddfe6850076892b7cdb029ecc0b08a06428200c
|
3 |
+
size 4991798414
|
model-00006-of-00007.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8d8fd601d8bc84783620827080d0d2ca6f690032923a3415b13b88ee339a090e
|
3 |
+
size 4991798414
|
model-00007-of-00007.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:55ecd75276302f49e29c82352e5b19a6b7148e42f3c818dcf0ad0fe786750f3b
|
3 |
+
size 1812157362
|
model.safetensors.index.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
modeling_helpingai.py
ADDED
@@ -0,0 +1,969 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Callable, Optional, Union
|
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, create_sliding_window_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 BaseModelOutputWithPast, CausalLMOutputWithPast
|
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.deprecation import deprecate_kwarg
|
24 |
+
from transformers.utils.generic import check_model_inputs
|
25 |
+
from .configuration_helpingai import HelpingAIConfig
|
26 |
+
|
27 |
+
|
28 |
+
@use_kernel_forward_from_hub("RMSNorm")
|
29 |
+
class HelpingAIRMSNorm(nn.Module):
|
30 |
+
def __init__(self, hidden_size, eps=1e-6):
|
31 |
+
"""
|
32 |
+
HelpingAIRMSNorm is equivalent to T5LayerNorm
|
33 |
+
"""
|
34 |
+
super().__init__()
|
35 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
36 |
+
self.variance_epsilon = eps
|
37 |
+
|
38 |
+
def forward(self, hidden_states):
|
39 |
+
input_dtype = hidden_states.dtype
|
40 |
+
hidden_states = hidden_states.to(torch.float32)
|
41 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
42 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
43 |
+
return self.weight * hidden_states.to(input_dtype)
|
44 |
+
|
45 |
+
def extra_repr(self):
|
46 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
47 |
+
|
48 |
+
|
49 |
+
class HelpingAISemanticEmotionReasoning(nn.Module):
|
50 |
+
"""
|
51 |
+
Structured Emotional Reasoning (SER) layer for emotional understanding and processing.
|
52 |
+
Maps emotions to semantic representations and provides contextual emotion analysis.
|
53 |
+
"""
|
54 |
+
def __init__(self, config: HelpingAIConfig):
|
55 |
+
super().__init__()
|
56 |
+
self.config = config
|
57 |
+
self.emotion_hidden_size = config.emotion_hidden_size
|
58 |
+
self.hidden_size = config.hidden_size
|
59 |
+
|
60 |
+
# Emotion detection and mapping
|
61 |
+
self.emotion_detector = nn.Linear(self.hidden_size, self.emotion_hidden_size)
|
62 |
+
self.emotion_mapper = nn.Linear(self.emotion_hidden_size, self.emotion_hidden_size)
|
63 |
+
|
64 |
+
# Contextual emotion analysis
|
65 |
+
self.emotion_context = nn.MultiheadAttention(
|
66 |
+
embed_dim=self.emotion_hidden_size,
|
67 |
+
num_heads=min(8, self.emotion_hidden_size // 64),
|
68 |
+
batch_first=True
|
69 |
+
)
|
70 |
+
|
71 |
+
# Emotion classification heads
|
72 |
+
self.primary_emotion = nn.Linear(self.emotion_hidden_size, 32) # Primary emotions
|
73 |
+
self.emotion_intensity = nn.Linear(self.emotion_hidden_size, 1) # Intensity score
|
74 |
+
self.emotion_valence = nn.Linear(self.emotion_hidden_size, 1) # Positive/negative
|
75 |
+
|
76 |
+
# Output projection
|
77 |
+
self.emotion_output = nn.Linear(self.emotion_hidden_size, self.hidden_size)
|
78 |
+
self.emotion_norm = HelpingAIRMSNorm(self.emotion_hidden_size, eps=config.rms_norm_eps)
|
79 |
+
|
80 |
+
# Activation
|
81 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
82 |
+
|
83 |
+
def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, dict]:
|
84 |
+
# Detect emotional content
|
85 |
+
emotion_features = self.act_fn(self.emotion_detector(hidden_states))
|
86 |
+
emotion_mapped = self.emotion_mapper(emotion_features)
|
87 |
+
emotion_mapped = self.emotion_norm(emotion_mapped)
|
88 |
+
|
89 |
+
# Contextual emotion analysis
|
90 |
+
emotion_context, attention_weights = self.emotion_context(
|
91 |
+
emotion_mapped, emotion_mapped, emotion_mapped
|
92 |
+
)
|
93 |
+
|
94 |
+
# Emotion analysis outputs
|
95 |
+
primary_emotions = self.primary_emotion(emotion_context)
|
96 |
+
emotion_intensity = torch.sigmoid(self.emotion_intensity(emotion_context))
|
97 |
+
emotion_valence = torch.tanh(self.emotion_valence(emotion_context))
|
98 |
+
|
99 |
+
# Project back to hidden size
|
100 |
+
emotion_output = self.emotion_output(emotion_context)
|
101 |
+
|
102 |
+
# Emotion metadata
|
103 |
+
emotion_metadata = {
|
104 |
+
"primary_emotions": primary_emotions,
|
105 |
+
"intensity": emotion_intensity,
|
106 |
+
"valence": emotion_valence,
|
107 |
+
"attention_weights": attention_weights
|
108 |
+
}
|
109 |
+
|
110 |
+
return emotion_output, emotion_metadata
|
111 |
+
|
112 |
+
|
113 |
+
class HelpingAIPerspectiveEmotionThreading(nn.Module):
|
114 |
+
"""
|
115 |
+
Parallel Empathic Threads (PET) layer for multi-threaded emotional reasoning.
|
116 |
+
Processes multiple perspective threads: relatable, supportive, motivational, analytical.
|
117 |
+
"""
|
118 |
+
def __init__(self, config: HelpingAIConfig):
|
119 |
+
super().__init__()
|
120 |
+
self.config = config
|
121 |
+
self.hidden_size = config.hidden_size
|
122 |
+
self.perspective_threads = config.perspective_threads
|
123 |
+
self.thread_hidden_size = config.emotion_hidden_size
|
124 |
+
|
125 |
+
# Thread-specific processors
|
126 |
+
self.thread_projections = nn.ModuleList([
|
127 |
+
nn.Linear(self.hidden_size, self.thread_hidden_size)
|
128 |
+
for _ in range(self.perspective_threads)
|
129 |
+
])
|
130 |
+
|
131 |
+
# Thread names for interpretability
|
132 |
+
self.thread_names = ["relatable", "supportive", "motivational", "analytical"][:self.perspective_threads]
|
133 |
+
|
134 |
+
# Cross-thread attention for perspective integration
|
135 |
+
self.cross_thread_attention = nn.MultiheadAttention(
|
136 |
+
embed_dim=self.thread_hidden_size,
|
137 |
+
num_heads=min(4, self.thread_hidden_size // 64),
|
138 |
+
batch_first=True
|
139 |
+
)
|
140 |
+
|
141 |
+
# Thread-specific processing layers
|
142 |
+
self.thread_processors = nn.ModuleList([
|
143 |
+
nn.Sequential(
|
144 |
+
nn.Linear(self.thread_hidden_size, self.thread_hidden_size * 2),
|
145 |
+
nn.GELU(),
|
146 |
+
nn.Linear(self.thread_hidden_size * 2, self.thread_hidden_size),
|
147 |
+
HelpingAIRMSNorm(self.thread_hidden_size, eps=config.rms_norm_eps)
|
148 |
+
)
|
149 |
+
for _ in range(self.perspective_threads)
|
150 |
+
])
|
151 |
+
|
152 |
+
# Output integration
|
153 |
+
self.thread_combiner = nn.Linear(
|
154 |
+
self.thread_hidden_size * self.perspective_threads,
|
155 |
+
self.hidden_size
|
156 |
+
)
|
157 |
+
|
158 |
+
# Thread importance weighting
|
159 |
+
self.thread_weights = nn.Parameter(torch.ones(self.perspective_threads))
|
160 |
+
|
161 |
+
def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, dict]:
|
162 |
+
batch_size, seq_len, _ = hidden_states.shape
|
163 |
+
|
164 |
+
# Process each perspective thread
|
165 |
+
thread_outputs = []
|
166 |
+
thread_metadata = {}
|
167 |
+
|
168 |
+
for i, (projection, processor, thread_name) in enumerate(
|
169 |
+
zip(self.thread_projections, self.thread_processors, self.thread_names)
|
170 |
+
):
|
171 |
+
# Project to thread space
|
172 |
+
thread_input = projection(hidden_states)
|
173 |
+
|
174 |
+
# Process thread-specific perspective
|
175 |
+
thread_output = processor(thread_input)
|
176 |
+
thread_outputs.append(thread_output)
|
177 |
+
|
178 |
+
# Store thread metadata
|
179 |
+
thread_metadata[f"{thread_name}_activation"] = torch.mean(torch.abs(thread_output))
|
180 |
+
|
181 |
+
# Stack threads for cross-thread attention
|
182 |
+
stacked_threads = torch.stack(thread_outputs, dim=2) # [batch, seq_len, num_threads, hidden]
|
183 |
+
stacked_threads = stacked_threads.reshape(batch_size * seq_len, self.perspective_threads, self.thread_hidden_size)
|
184 |
+
|
185 |
+
# Cross-thread attention for perspective integration
|
186 |
+
integrated_threads, cross_attention = self.cross_thread_attention(
|
187 |
+
stacked_threads, stacked_threads, stacked_threads
|
188 |
+
)
|
189 |
+
|
190 |
+
# Apply thread importance weighting
|
191 |
+
thread_weights_normalized = torch.softmax(self.thread_weights, dim=0)
|
192 |
+
weighted_threads = integrated_threads * thread_weights_normalized.unsqueeze(0).unsqueeze(-1)
|
193 |
+
|
194 |
+
# Combine threads - use reshape instead of view for memory layout compatibility
|
195 |
+
combined_threads = weighted_threads.reshape(batch_size, seq_len, -1)
|
196 |
+
final_output = self.thread_combiner(combined_threads)
|
197 |
+
|
198 |
+
# Thread metadata
|
199 |
+
thread_metadata.update({
|
200 |
+
"thread_weights": thread_weights_normalized,
|
201 |
+
"cross_attention": cross_attention,
|
202 |
+
"thread_activations": {
|
203 |
+
name: torch.mean(output) for name, output in zip(self.thread_names, thread_outputs)
|
204 |
+
}
|
205 |
+
})
|
206 |
+
|
207 |
+
return final_output, thread_metadata
|
208 |
+
|
209 |
+
|
210 |
+
class HelpingAIMultiStageThinking(nn.Module):
|
211 |
+
"""
|
212 |
+
Multi-stage thinking module for internal reasoning and reflection processes.
|
213 |
+
Implements cascaded thinking stages with simplified feedback loops.
|
214 |
+
"""
|
215 |
+
def __init__(self, config: HelpingAIConfig):
|
216 |
+
super().__init__()
|
217 |
+
self.config = config
|
218 |
+
self.hidden_size = config.hidden_size
|
219 |
+
self.thinking_stages = config.num_thinking_stages
|
220 |
+
self.thinking_depth = config.thinking_depth
|
221 |
+
|
222 |
+
# Thinking stage processors
|
223 |
+
self.thinking_layers = nn.ModuleList([
|
224 |
+
nn.Sequential(
|
225 |
+
nn.Linear(self.hidden_size, self.hidden_size),
|
226 |
+
nn.GELU(),
|
227 |
+
nn.Linear(self.hidden_size, self.hidden_size),
|
228 |
+
HelpingAIRMSNorm(self.hidden_size, eps=config.rms_norm_eps)
|
229 |
+
)
|
230 |
+
for _ in range(self.thinking_stages)
|
231 |
+
])
|
232 |
+
|
233 |
+
# Simple reflection mechanism without complex attention
|
234 |
+
self.reflection_layers = nn.ModuleList([
|
235 |
+
nn.Linear(self.hidden_size, self.hidden_size)
|
236 |
+
for _ in range(self.thinking_stages - 1)
|
237 |
+
])
|
238 |
+
|
239 |
+
# Stage transition gates
|
240 |
+
self.stage_gates = nn.ModuleList([
|
241 |
+
nn.Linear(self.hidden_size, 1) for _ in range(self.thinking_stages - 1)
|
242 |
+
])
|
243 |
+
|
244 |
+
# Thinking combination weights
|
245 |
+
self.stage_combiner = nn.Linear(self.thinking_stages * self.hidden_size, self.hidden_size)
|
246 |
+
|
247 |
+
def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, dict]:
|
248 |
+
batch_size, seq_len, _ = hidden_states.shape
|
249 |
+
thinking_outputs = []
|
250 |
+
thinking_metadata = {}
|
251 |
+
|
252 |
+
current_thought = hidden_states
|
253 |
+
|
254 |
+
# Multi-stage thinking process
|
255 |
+
for stage_idx, stage_processor in enumerate(self.thinking_layers):
|
256 |
+
# Process current thinking stage
|
257 |
+
current_thought = stage_processor(current_thought)
|
258 |
+
|
259 |
+
# Store stage output
|
260 |
+
thinking_outputs.append(current_thought)
|
261 |
+
thinking_metadata[f"stage_{stage_idx}_activation"] = torch.mean(torch.abs(current_thought)).item()
|
262 |
+
|
263 |
+
# Apply reflection if not the last stage
|
264 |
+
if stage_idx < self.thinking_stages - 1:
|
265 |
+
# Simple reflection mechanism
|
266 |
+
reflection = self.reflection_layers[stage_idx](current_thought)
|
267 |
+
current_thought = current_thought + 0.1 * reflection # Small reflection influence
|
268 |
+
|
269 |
+
# Stage transition gating
|
270 |
+
gate_weight = torch.sigmoid(self.stage_gates[stage_idx](current_thought))
|
271 |
+
current_thought = gate_weight * current_thought + (1 - gate_weight) * hidden_states
|
272 |
+
|
273 |
+
# Combine all thinking stages
|
274 |
+
all_thoughts = torch.cat(thinking_outputs, dim=-1) # Concatenate along hidden dimension
|
275 |
+
final_thought = self.stage_combiner(all_thoughts)
|
276 |
+
|
277 |
+
thinking_metadata["stage_contributions"] = [
|
278 |
+
torch.mean(torch.abs(output)).item() for output in thinking_outputs
|
279 |
+
]
|
280 |
+
|
281 |
+
return final_thought, thinking_metadata
|
282 |
+
|
283 |
+
|
284 |
+
class HelpingAIMLP(nn.Module):
|
285 |
+
def __init__(self, config):
|
286 |
+
super().__init__()
|
287 |
+
self.config = config
|
288 |
+
self.hidden_size = config.hidden_size
|
289 |
+
self.intermediate_size = config.intermediate_size
|
290 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
291 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
292 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
293 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
294 |
+
|
295 |
+
# Enhanced MLP with thinking modules
|
296 |
+
if hasattr(config, 'use_emotional_reasoning') and config.use_emotional_reasoning:
|
297 |
+
self.thinking_module = HelpingAIMultiStageThinking(config)
|
298 |
+
self.use_thinking = True
|
299 |
+
else:
|
300 |
+
self.use_thinking = False
|
301 |
+
|
302 |
+
# Reasoning temperature for controlled generation
|
303 |
+
self.reasoning_temperature = getattr(config, 'reasoning_temperature', 1.0)
|
304 |
+
|
305 |
+
def forward(self, x):
|
306 |
+
# Standard MLP forward pass
|
307 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
308 |
+
|
309 |
+
# Apply multi-stage thinking if enabled
|
310 |
+
if self.use_thinking:
|
311 |
+
thinking_output, thinking_metadata = self.thinking_module(down_proj)
|
312 |
+
# Apply reasoning temperature
|
313 |
+
down_proj = down_proj + (thinking_output * self.reasoning_temperature)
|
314 |
+
|
315 |
+
return down_proj
|
316 |
+
|
317 |
+
|
318 |
+
def rotate_half(x):
|
319 |
+
"""Rotates half the hidden dims of the input."""
|
320 |
+
x1 = x[..., : x.shape[-1] // 2]
|
321 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
322 |
+
return torch.cat((-x2, x1), dim=-1)
|
323 |
+
|
324 |
+
|
325 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
326 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
327 |
+
|
328 |
+
Args:
|
329 |
+
q (`torch.Tensor`): The query tensor.
|
330 |
+
k (`torch.Tensor`): The key tensor.
|
331 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
332 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
333 |
+
position_ids (`torch.Tensor`, *optional*):
|
334 |
+
Deprecated and unused.
|
335 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
336 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
337 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
338 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
339 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
340 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
341 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
342 |
+
Returns:
|
343 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
344 |
+
"""
|
345 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
346 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
347 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
348 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
349 |
+
return q_embed, k_embed
|
350 |
+
|
351 |
+
|
352 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
353 |
+
"""
|
354 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
355 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
356 |
+
"""
|
357 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
358 |
+
if n_rep == 1:
|
359 |
+
return hidden_states
|
360 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
361 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
362 |
+
|
363 |
+
|
364 |
+
def eager_attention_forward(
|
365 |
+
module: nn.Module,
|
366 |
+
query: torch.Tensor,
|
367 |
+
key: torch.Tensor,
|
368 |
+
value: torch.Tensor,
|
369 |
+
attention_mask: Optional[torch.Tensor],
|
370 |
+
scaling: float,
|
371 |
+
dropout: float = 0.0,
|
372 |
+
**kwargs: Unpack[TransformersKwargs],
|
373 |
+
):
|
374 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
375 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
376 |
+
|
377 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
378 |
+
if attention_mask is not None:
|
379 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
380 |
+
attn_weights = attn_weights + causal_mask
|
381 |
+
|
382 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
383 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
384 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
385 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
386 |
+
|
387 |
+
return attn_output, attn_weights
|
388 |
+
|
389 |
+
|
390 |
+
class HelpingAIAttention(nn.Module):
|
391 |
+
"""Multi-headed attention with specialized emotional and empathetic reasoning capabilities"""
|
392 |
+
|
393 |
+
def __init__(self, config: HelpingAIConfig, layer_idx: int):
|
394 |
+
super().__init__()
|
395 |
+
self.config = config
|
396 |
+
self.layer_idx = layer_idx
|
397 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
398 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
399 |
+
self.scaling = self.head_dim**-0.5
|
400 |
+
self.attention_dropout = config.attention_dropout
|
401 |
+
self.is_causal = True
|
402 |
+
|
403 |
+
self.q_proj = nn.Linear(
|
404 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
405 |
+
)
|
406 |
+
self.k_proj = nn.Linear(
|
407 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
408 |
+
)
|
409 |
+
self.v_proj = nn.Linear(
|
410 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
411 |
+
)
|
412 |
+
self.o_proj = nn.Linear(
|
413 |
+
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
|
414 |
+
)
|
415 |
+
self.q_norm = HelpingAIRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
416 |
+
self.k_norm = HelpingAIRMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
417 |
+
self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
|
418 |
+
|
419 |
+
# Enhanced emotional and empathetic attention
|
420 |
+
if hasattr(config, 'use_emotional_reasoning') and config.use_emotional_reasoning:
|
421 |
+
self.num_emotion_heads = getattr(config, 'num_emotion_heads', 4)
|
422 |
+
self.empathy_scaling_factor = getattr(config, 'empathy_scaling_factor', 1.2)
|
423 |
+
|
424 |
+
# Specialized emotion attention projections
|
425 |
+
self.emotion_q_proj = nn.Linear(config.hidden_size, self.num_emotion_heads * self.head_dim, bias=False)
|
426 |
+
self.emotion_k_proj = nn.Linear(config.hidden_size, self.num_emotion_heads * self.head_dim, bias=False)
|
427 |
+
self.emotion_v_proj = nn.Linear(config.hidden_size, self.num_emotion_heads * self.head_dim, bias=False)
|
428 |
+
|
429 |
+
# Empathy enhancement layer
|
430 |
+
self.empathy_enhancer = nn.Sequential(
|
431 |
+
nn.Linear(config.hidden_size, config.hidden_size // 2),
|
432 |
+
nn.GELU(),
|
433 |
+
nn.Linear(config.hidden_size // 2, config.num_attention_heads),
|
434 |
+
nn.Softmax(dim=-1)
|
435 |
+
)
|
436 |
+
|
437 |
+
self.use_emotional_attention = True
|
438 |
+
else:
|
439 |
+
self.use_emotional_attention = False
|
440 |
+
|
441 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
442 |
+
def forward(
|
443 |
+
self,
|
444 |
+
hidden_states: torch.Tensor,
|
445 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
446 |
+
attention_mask: Optional[torch.Tensor],
|
447 |
+
past_key_values: Optional[Cache] = None,
|
448 |
+
cache_position: Optional[torch.LongTensor] = None,
|
449 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
450 |
+
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
|
451 |
+
input_shape = hidden_states.shape[:-1]
|
452 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
453 |
+
|
454 |
+
# Standard attention processing
|
455 |
+
query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
456 |
+
key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
457 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
458 |
+
|
459 |
+
cos, sin = position_embeddings
|
460 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
461 |
+
|
462 |
+
if past_key_values is not None:
|
463 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
464 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
465 |
+
|
466 |
+
# Enhanced emotional attention processing
|
467 |
+
if self.use_emotional_attention:
|
468 |
+
# Compute empathy weights
|
469 |
+
empathy_weights = self.empathy_enhancer(hidden_states.mean(dim=1)) # [batch, num_heads]
|
470 |
+
|
471 |
+
# Emotional query, key, value computation
|
472 |
+
emotion_query = self.emotion_q_proj(hidden_states).view(*input_shape, self.num_emotion_heads, self.head_dim).transpose(1, 2)
|
473 |
+
emotion_key = self.emotion_k_proj(hidden_states).view(*input_shape, self.num_emotion_heads, self.head_dim).transpose(1, 2)
|
474 |
+
emotion_value = self.emotion_v_proj(hidden_states).view(*input_shape, self.num_emotion_heads, self.head_dim).transpose(1, 2)
|
475 |
+
|
476 |
+
# Apply rotary embeddings to emotional attention
|
477 |
+
emotion_query, emotion_key = apply_rotary_pos_emb(emotion_query, emotion_key, cos, sin)
|
478 |
+
|
479 |
+
# Emotional attention computation
|
480 |
+
emotion_scaling = (self.head_dim ** -0.5) * self.empathy_scaling_factor
|
481 |
+
emotion_attn_weights = torch.matmul(emotion_query, emotion_key.transpose(2, 3)) * emotion_scaling
|
482 |
+
|
483 |
+
if attention_mask is not None:
|
484 |
+
emotion_causal_mask = attention_mask[:, :, :, :emotion_key.shape[-2]]
|
485 |
+
emotion_attn_weights = emotion_attn_weights + emotion_causal_mask
|
486 |
+
|
487 |
+
emotion_attn_weights = nn.functional.softmax(emotion_attn_weights, dim=-1, dtype=torch.float32).to(emotion_query.dtype)
|
488 |
+
emotion_output = torch.matmul(emotion_attn_weights, emotion_value)
|
489 |
+
|
490 |
+
# Integrate emotional attention with standard attention
|
491 |
+
# Pad or truncate emotional attention to match standard attention heads
|
492 |
+
if self.num_emotion_heads < self.config.num_attention_heads:
|
493 |
+
padding_heads = self.config.num_attention_heads - self.num_emotion_heads
|
494 |
+
emotion_padding = torch.zeros(
|
495 |
+
*emotion_output.shape[:-3], padding_heads, *emotion_output.shape[-2:],
|
496 |
+
device=emotion_output.device, dtype=emotion_output.dtype
|
497 |
+
)
|
498 |
+
emotion_output = torch.cat([emotion_output, emotion_padding], dim=1)
|
499 |
+
|
500 |
+
# Standard attention computation
|
501 |
+
attention_interface: Callable = eager_attention_forward
|
502 |
+
if self.config._attn_implementation != "eager":
|
503 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
504 |
+
|
505 |
+
attn_output, attn_weights = attention_interface(
|
506 |
+
self,
|
507 |
+
query_states,
|
508 |
+
key_states,
|
509 |
+
value_states,
|
510 |
+
attention_mask,
|
511 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
512 |
+
scaling=self.scaling,
|
513 |
+
sliding_window=self.sliding_window,
|
514 |
+
**kwargs,
|
515 |
+
)
|
516 |
+
|
517 |
+
# Blend standard and emotional attention if emotional reasoning is enabled
|
518 |
+
if self.use_emotional_attention:
|
519 |
+
# For now, use a simplified approach - just apply empathy scaling
|
520 |
+
# This avoids the complex tensor dimension matching issues
|
521 |
+
batch_size, num_heads, seq_len, head_dim = attn_output.shape
|
522 |
+
|
523 |
+
# Get average empathy weight per batch
|
524 |
+
empathy_scale = torch.mean(empathy_weights, dim=1, keepdim=True) # [batch, 1]
|
525 |
+
empathy_scale = empathy_scale.view(batch_size, 1, 1, 1) # [batch, 1, 1, 1]
|
526 |
+
empathy_scale = empathy_scale.expand(batch_size, num_heads, seq_len, head_dim)
|
527 |
+
|
528 |
+
# Apply empathy scaling to attention output
|
529 |
+
attn_output = attn_output * (1.0 + empathy_scale * 0.1) # Small empathy influence
|
530 |
+
|
531 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
532 |
+
attn_output = self.o_proj(attn_output)
|
533 |
+
return attn_output, attn_weights
|
534 |
+
|
535 |
+
|
536 |
+
class HelpingAIDecoderLayer(GradientCheckpointingLayer):
|
537 |
+
def __init__(self, config: HelpingAIConfig, layer_idx: int):
|
538 |
+
super().__init__()
|
539 |
+
self.hidden_size = config.hidden_size
|
540 |
+
self.layer_idx = layer_idx
|
541 |
+
|
542 |
+
self.self_attn = HelpingAIAttention(config=config, layer_idx=layer_idx)
|
543 |
+
self.mlp = HelpingAIMLP(config)
|
544 |
+
self.input_layernorm = HelpingAIRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
545 |
+
self.post_attention_layernorm = HelpingAIRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
546 |
+
self.attention_type = config.layer_types[layer_idx]
|
547 |
+
|
548 |
+
# Enhanced reasoning layers
|
549 |
+
if hasattr(config, 'use_emotional_reasoning') and config.use_emotional_reasoning:
|
550 |
+
self.ser_layer = HelpingAISemanticEmotionReasoning(config)
|
551 |
+
self.use_ser = True
|
552 |
+
else:
|
553 |
+
self.use_ser = False
|
554 |
+
|
555 |
+
if hasattr(config, 'use_perspective_threading') and config.use_perspective_threading:
|
556 |
+
self.pet_layer = HelpingAIPerspectiveEmotionThreading(config)
|
557 |
+
self.use_pet = True
|
558 |
+
else:
|
559 |
+
self.use_pet = False
|
560 |
+
|
561 |
+
# Reasoning integration layers
|
562 |
+
if self.use_ser or self.use_pet:
|
563 |
+
self.reasoning_norm = HelpingAIRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
564 |
+
self.reasoning_gate = nn.Linear(config.hidden_size, 1)
|
565 |
+
|
566 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
567 |
+
def forward(
|
568 |
+
self,
|
569 |
+
hidden_states: torch.Tensor,
|
570 |
+
attention_mask: Optional[torch.Tensor] = None,
|
571 |
+
position_ids: Optional[torch.LongTensor] = None,
|
572 |
+
past_key_values: Optional[Cache] = None,
|
573 |
+
use_cache: Optional[bool] = False,
|
574 |
+
cache_position: Optional[torch.LongTensor] = None,
|
575 |
+
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
|
576 |
+
**kwargs: Unpack[TransformersKwargs],
|
577 |
+
) -> torch.Tensor:
|
578 |
+
residual = hidden_states
|
579 |
+
hidden_states = self.input_layernorm(hidden_states)
|
580 |
+
|
581 |
+
# Self Attention
|
582 |
+
hidden_states, attention_weights = self.self_attn(
|
583 |
+
hidden_states=hidden_states,
|
584 |
+
attention_mask=attention_mask,
|
585 |
+
position_ids=position_ids,
|
586 |
+
past_key_values=past_key_values,
|
587 |
+
use_cache=use_cache,
|
588 |
+
cache_position=cache_position,
|
589 |
+
position_embeddings=position_embeddings,
|
590 |
+
**kwargs,
|
591 |
+
)
|
592 |
+
hidden_states = residual + hidden_states
|
593 |
+
|
594 |
+
# Enhanced reasoning processing
|
595 |
+
reasoning_outputs = []
|
596 |
+
reasoning_metadata = {}
|
597 |
+
|
598 |
+
if self.use_ser:
|
599 |
+
# Semantic Emotion Reasoning
|
600 |
+
ser_output, ser_meta = self.ser_layer(hidden_states)
|
601 |
+
reasoning_outputs.append(ser_output)
|
602 |
+
reasoning_metadata['ser'] = ser_meta
|
603 |
+
|
604 |
+
if self.use_pet:
|
605 |
+
# Perspective Emotion Threading
|
606 |
+
pet_output, pet_meta = self.pet_layer(hidden_states)
|
607 |
+
reasoning_outputs.append(pet_output)
|
608 |
+
reasoning_metadata['pet'] = pet_meta
|
609 |
+
|
610 |
+
# Integrate reasoning outputs if any
|
611 |
+
if reasoning_outputs:
|
612 |
+
# Combine reasoning outputs
|
613 |
+
combined_reasoning = torch.stack(reasoning_outputs, dim=0).mean(dim=0)
|
614 |
+
combined_reasoning = self.reasoning_norm(combined_reasoning)
|
615 |
+
|
616 |
+
# Apply gating to control reasoning influence
|
617 |
+
reasoning_gate = torch.sigmoid(self.reasoning_gate(hidden_states))
|
618 |
+
hidden_states = hidden_states + (reasoning_gate * combined_reasoning)
|
619 |
+
|
620 |
+
# Fully Connected (MLP)
|
621 |
+
residual = hidden_states
|
622 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
623 |
+
hidden_states = self.mlp(hidden_states)
|
624 |
+
hidden_states = residual + hidden_states
|
625 |
+
|
626 |
+
# Store reasoning metadata for analysis (optional)
|
627 |
+
if hasattr(hidden_states, '_reasoning_metadata'):
|
628 |
+
hidden_states._reasoning_metadata = reasoning_metadata
|
629 |
+
|
630 |
+
return hidden_states
|
631 |
+
|
632 |
+
|
633 |
+
@auto_docstring
|
634 |
+
class HelpingAIPreTrainedModel(PreTrainedModel):
|
635 |
+
config: HelpingAIConfig
|
636 |
+
base_model_prefix = "model"
|
637 |
+
supports_gradient_checkpointing = True
|
638 |
+
_no_split_modules = ["HelpingAIDecoderLayer"]
|
639 |
+
_skip_keys_device_placement = ["past_key_values"]
|
640 |
+
_supports_flash_attn = True
|
641 |
+
_supports_sdpa = True
|
642 |
+
_supports_flex_attn = True
|
643 |
+
|
644 |
+
_can_compile_fullgraph = True
|
645 |
+
_supports_attention_backend = True
|
646 |
+
_can_record_outputs = {
|
647 |
+
"hidden_states": HelpingAIDecoderLayer,
|
648 |
+
"attentions": HelpingAIAttention,
|
649 |
+
}
|
650 |
+
|
651 |
+
|
652 |
+
class HelpingAIRotaryEmbedding(nn.Module):
|
653 |
+
inv_freq: torch.Tensor # fix linting for `register_buffer`
|
654 |
+
|
655 |
+
def __init__(self, config: HelpingAIConfig, device=None):
|
656 |
+
super().__init__()
|
657 |
+
# BC: "rope_type" was originally "type"
|
658 |
+
if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
|
659 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
660 |
+
else:
|
661 |
+
self.rope_type = "default"
|
662 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
663 |
+
self.original_max_seq_len = config.max_position_embeddings
|
664 |
+
|
665 |
+
self.config = config
|
666 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
667 |
+
|
668 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
|
669 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
670 |
+
self.original_inv_freq = self.inv_freq
|
671 |
+
|
672 |
+
@torch.no_grad()
|
673 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
674 |
+
def forward(self, x, position_ids):
|
675 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
676 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
677 |
+
|
678 |
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
679 |
+
with torch.autocast(device_type=device_type, enabled=False): # Force float32
|
680 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
681 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
682 |
+
cos = emb.cos() * self.attention_scaling
|
683 |
+
sin = emb.sin() * self.attention_scaling
|
684 |
+
|
685 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
686 |
+
|
687 |
+
|
688 |
+
@auto_docstring
|
689 |
+
class HelpingAIModel(HelpingAIPreTrainedModel):
|
690 |
+
def __init__(self, config: HelpingAIConfig):
|
691 |
+
super().__init__(config)
|
692 |
+
self.padding_idx = config.pad_token_id
|
693 |
+
self.vocab_size = config.vocab_size
|
694 |
+
|
695 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
696 |
+
self.layers = nn.ModuleList(
|
697 |
+
[HelpingAIDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
698 |
+
)
|
699 |
+
self.norm = HelpingAIRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
700 |
+
self.rotary_emb = HelpingAIRotaryEmbedding(config=config)
|
701 |
+
self.gradient_checkpointing = False
|
702 |
+
self.has_sliding_layers = "sliding_attention" in self.config.layer_types
|
703 |
+
|
704 |
+
# Initialize weights and apply final processing
|
705 |
+
self.post_init()
|
706 |
+
|
707 |
+
@check_model_inputs
|
708 |
+
@auto_docstring
|
709 |
+
def forward(
|
710 |
+
self,
|
711 |
+
input_ids: Optional[torch.LongTensor] = None,
|
712 |
+
attention_mask: Optional[torch.Tensor] = None,
|
713 |
+
position_ids: Optional[torch.LongTensor] = None,
|
714 |
+
past_key_values: Optional[Cache] = None,
|
715 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
716 |
+
use_cache: Optional[bool] = None,
|
717 |
+
cache_position: Optional[torch.LongTensor] = None,
|
718 |
+
**kwargs: Unpack[TransformersKwargs],
|
719 |
+
) -> BaseModelOutputWithPast:
|
720 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
721 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
722 |
+
|
723 |
+
if inputs_embeds is None:
|
724 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
725 |
+
|
726 |
+
if use_cache and past_key_values is None:
|
727 |
+
past_key_values = DynamicCache()
|
728 |
+
|
729 |
+
if cache_position is None:
|
730 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
731 |
+
cache_position = torch.arange(
|
732 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
733 |
+
)
|
734 |
+
|
735 |
+
if position_ids is None:
|
736 |
+
position_ids = cache_position.unsqueeze(0)
|
737 |
+
|
738 |
+
# It may already have been prepared by e.g. `generate`
|
739 |
+
if not isinstance(causal_mask_mapping := attention_mask, dict):
|
740 |
+
# Prepare mask arguments
|
741 |
+
mask_kwargs = {
|
742 |
+
"config": self.config,
|
743 |
+
"input_embeds": inputs_embeds,
|
744 |
+
"attention_mask": attention_mask,
|
745 |
+
"cache_position": cache_position,
|
746 |
+
"past_key_values": past_key_values,
|
747 |
+
"position_ids": position_ids,
|
748 |
+
}
|
749 |
+
# Create the masks
|
750 |
+
causal_mask_mapping = {
|
751 |
+
"full_attention": create_causal_mask(**mask_kwargs),
|
752 |
+
}
|
753 |
+
# The sliding window alternating layers are not always activated depending on the config
|
754 |
+
if self.has_sliding_layers:
|
755 |
+
causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
|
756 |
+
|
757 |
+
hidden_states = inputs_embeds
|
758 |
+
|
759 |
+
# create position embeddings to be shared across the decoder layers
|
760 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
761 |
+
|
762 |
+
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
|
763 |
+
hidden_states = decoder_layer(
|
764 |
+
hidden_states,
|
765 |
+
attention_mask=causal_mask_mapping[decoder_layer.attention_type],
|
766 |
+
position_ids=position_ids,
|
767 |
+
past_key_values=past_key_values,
|
768 |
+
use_cache=use_cache,
|
769 |
+
cache_position=cache_position,
|
770 |
+
position_embeddings=position_embeddings,
|
771 |
+
**kwargs,
|
772 |
+
)
|
773 |
+
|
774 |
+
hidden_states = self.norm(hidden_states)
|
775 |
+
return BaseModelOutputWithPast(
|
776 |
+
last_hidden_state=hidden_states,
|
777 |
+
past_key_values=past_key_values if use_cache else None,
|
778 |
+
)
|
779 |
+
|
780 |
+
|
781 |
+
@auto_docstring
|
782 |
+
class HelpingAIForCausalLM(HelpingAIPreTrainedModel, GenerationMixin):
|
783 |
+
_tied_weights_keys = ["lm_head.weight"]
|
784 |
+
_tp_plan = {"lm_head": "colwise_rep"}
|
785 |
+
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
786 |
+
|
787 |
+
def __init__(self, config):
|
788 |
+
super().__init__(config)
|
789 |
+
self.model = HelpingAIModel(config)
|
790 |
+
self.vocab_size = config.vocab_size
|
791 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
792 |
+
|
793 |
+
# Enhanced structured output support
|
794 |
+
if hasattr(config, 'structured_output_vocab_size') and config.structured_output_vocab_size > 0:
|
795 |
+
self.structured_vocab_size = config.structured_output_vocab_size
|
796 |
+
self.structured_lm_head = nn.Linear(config.hidden_size, self.structured_vocab_size, bias=False)
|
797 |
+
self.use_structured_output = True
|
798 |
+
|
799 |
+
# Special token embeddings for structured reasoning
|
800 |
+
self.structured_token_embeddings = nn.Embedding(self.structured_vocab_size, config.hidden_size)
|
801 |
+
|
802 |
+
# Reasoning mode classifier
|
803 |
+
self.reasoning_mode_classifier = nn.Sequential(
|
804 |
+
nn.Linear(config.hidden_size, config.hidden_size // 2),
|
805 |
+
nn.GELU(),
|
806 |
+
nn.Linear(config.hidden_size // 2, 4), # think, ser, pet, normal
|
807 |
+
nn.Softmax(dim=-1)
|
808 |
+
)
|
809 |
+
else:
|
810 |
+
self.use_structured_output = False
|
811 |
+
|
812 |
+
# Initialize weights and apply final processing
|
813 |
+
self.post_init()
|
814 |
+
|
815 |
+
def set_decoder(self, decoder):
|
816 |
+
self.model = decoder
|
817 |
+
|
818 |
+
def get_decoder(self):
|
819 |
+
return self.model
|
820 |
+
|
821 |
+
def get_reasoning_mode_probabilities(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
822 |
+
"""Get probabilities for different reasoning modes: think, ser, pet, normal"""
|
823 |
+
if self.use_structured_output:
|
824 |
+
# Use the last token's hidden state for mode classification
|
825 |
+
last_hidden = hidden_states[:, -1, :] # [batch_size, hidden_size]
|
826 |
+
mode_probs = self.reasoning_mode_classifier(last_hidden)
|
827 |
+
return mode_probs
|
828 |
+
return None
|
829 |
+
|
830 |
+
@can_return_tuple
|
831 |
+
@auto_docstring
|
832 |
+
def forward(
|
833 |
+
self,
|
834 |
+
input_ids: Optional[torch.LongTensor] = None,
|
835 |
+
attention_mask: Optional[torch.Tensor] = None,
|
836 |
+
position_ids: Optional[torch.LongTensor] = None,
|
837 |
+
past_key_values: Optional[Cache] = None,
|
838 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
839 |
+
labels: Optional[torch.LongTensor] = None,
|
840 |
+
use_cache: Optional[bool] = None,
|
841 |
+
cache_position: Optional[torch.LongTensor] = None,
|
842 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
843 |
+
return_reasoning_metadata: Optional[bool] = False,
|
844 |
+
**kwargs: Unpack[TransformersKwargs],
|
845 |
+
) -> CausalLMOutputWithPast:
|
846 |
+
r"""
|
847 |
+
Enhanced HelpingAI forward pass with structured reasoning support.
|
848 |
+
|
849 |
+
Args:
|
850 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
851 |
+
Indices of input sequence tokens in the vocabulary.
|
852 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
853 |
+
Mask to avoid performing attention on padding token indices.
|
854 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
855 |
+
Indices of positions of each input sequence tokens in the position embeddings.
|
856 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
857 |
+
Pre-computed hidden-states that can be used to speed up autoregressive decoding.
|
858 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
859 |
+
Embedded representation of the input tokens. Can be used instead of `input_ids`.
|
860 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
861 |
+
Labels for computing the masked language modeling loss.
|
862 |
+
use_cache (`bool`, *optional*):
|
863 |
+
If set to `True`, past key values are returned and can be used to speed up decoding.
|
864 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
865 |
+
Indices depicting the position of the input tokens in the sequence.
|
866 |
+
logits_to_keep (`Union[int, torch.Tensor]`, *optional*, defaults to 0):
|
867 |
+
Number of logits to keep from the end of the sequence.
|
868 |
+
return_reasoning_metadata (`bool`, *optional*, defaults to `False`):
|
869 |
+
Whether to return reasoning metadata including SER and PET analysis for structured reasoning.
|
870 |
+
|
871 |
+
Returns:
|
872 |
+
`CausalLMOutputWithPast`: Model output containing logits, past key values, and optional reasoning metadata.
|
873 |
+
|
874 |
+
Example:
|
875 |
+
|
876 |
+
```python
|
877 |
+
>>> from transformers import AutoTokenizer, HelpingAIForCausalLM
|
878 |
+
|
879 |
+
>>> model = HelpingAIForCausalLM.from_pretrained("HelpingAI/HelpingAI-8B")
|
880 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("HelpingAI/HelpingAI-8B")
|
881 |
+
|
882 |
+
>>> # Standard generation
|
883 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
884 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
885 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
886 |
+
>>> response = tokenizer.batch_decode(generate_ids, skip_special_tokens=True)[0]
|
887 |
+
|
888 |
+
>>> # Structured reasoning generation
|
889 |
+
>>> outputs = model(inputs.input_ids, return_reasoning_metadata=True)
|
890 |
+
>>> reasoning_modes = model.get_reasoning_mode_probabilities(outputs.hidden_states)
|
891 |
+
```"""
|
892 |
+
outputs: BaseModelOutputWithPast = self.model(
|
893 |
+
input_ids=input_ids,
|
894 |
+
attention_mask=attention_mask,
|
895 |
+
position_ids=position_ids,
|
896 |
+
past_key_values=past_key_values,
|
897 |
+
inputs_embeds=inputs_embeds,
|
898 |
+
use_cache=use_cache,
|
899 |
+
cache_position=cache_position,
|
900 |
+
**kwargs,
|
901 |
+
)
|
902 |
+
|
903 |
+
hidden_states = outputs.last_hidden_state
|
904 |
+
|
905 |
+
# Standard language modeling head
|
906 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
907 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
908 |
+
|
909 |
+
# Enhanced structured output logits
|
910 |
+
structured_logits = None
|
911 |
+
reasoning_mode_probs = None
|
912 |
+
if self.use_structured_output:
|
913 |
+
structured_logits = self.structured_lm_head(hidden_states[:, slice_indices, :])
|
914 |
+
reasoning_mode_probs = self.get_reasoning_mode_probabilities(hidden_states)
|
915 |
+
|
916 |
+
loss = None
|
917 |
+
if labels is not None:
|
918 |
+
# Standard loss computation
|
919 |
+
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
|
920 |
+
|
921 |
+
# Add structured output loss if applicable
|
922 |
+
if self.use_structured_output and structured_logits is not None:
|
923 |
+
# Additional loss term for structured reasoning (if labels include structured tokens)
|
924 |
+
structured_loss_weight = 0.1 # Weight for structured output loss
|
925 |
+
structured_loss = self.loss_function(
|
926 |
+
logits=structured_logits,
|
927 |
+
labels=labels,
|
928 |
+
vocab_size=self.structured_vocab_size,
|
929 |
+
**kwargs
|
930 |
+
)
|
931 |
+
loss = loss + (structured_loss_weight * structured_loss)
|
932 |
+
|
933 |
+
# Prepare output with enhanced reasoning metadata
|
934 |
+
output = CausalLMOutputWithPast(
|
935 |
+
loss=loss,
|
936 |
+
logits=logits,
|
937 |
+
past_key_values=outputs.past_key_values,
|
938 |
+
hidden_states=outputs.hidden_states,
|
939 |
+
attentions=outputs.attentions,
|
940 |
+
)
|
941 |
+
|
942 |
+
# Add custom attributes for reasoning
|
943 |
+
if return_reasoning_metadata and self.use_structured_output:
|
944 |
+
output.structured_logits = structured_logits
|
945 |
+
output.reasoning_mode_probabilities = reasoning_mode_probs
|
946 |
+
|
947 |
+
return output
|
948 |
+
|
949 |
+
|
950 |
+
class HelpingAIForSequenceClassification(GenericForSequenceClassification, HelpingAIPreTrainedModel):
|
951 |
+
pass
|
952 |
+
|
953 |
+
|
954 |
+
class HelpingAIForTokenClassification(GenericForTokenClassification, HelpingAIPreTrainedModel):
|
955 |
+
pass
|
956 |
+
|
957 |
+
|
958 |
+
class HelpingAIForQuestionAnswering(GenericForQuestionAnswering, HelpingAIPreTrainedModel):
|
959 |
+
base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model`
|
960 |
+
|
961 |
+
|
962 |
+
__all__ = [
|
963 |
+
"HelpingAIForCausalLM",
|
964 |
+
"HelpingAIForQuestionAnswering",
|
965 |
+
"HelpingAIPreTrainedModel",
|
966 |
+
"HelpingAIModel",
|
967 |
+
"HelpingAIForSequenceClassification",
|
968 |
+
"HelpingAIForTokenClassification",
|
969 |
+
]
|
special_tokens_map.json
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"additional_special_tokens": [
|
3 |
+
"<|im_start|>",
|
4 |
+
"<|im_end|>",
|
5 |
+
"<|object_ref_start|>",
|
6 |
+
"<|object_ref_end|>",
|
7 |
+
"<|box_start|>",
|
8 |
+
"<|box_end|>",
|
9 |
+
"<|quad_start|>",
|
10 |
+
"<|quad_end|>",
|
11 |
+
"<|vision_start|>",
|
12 |
+
"<|vision_end|>",
|
13 |
+
"<|vision_pad|>",
|
14 |
+
"<|image_pad|>",
|
15 |
+
"<|video_pad|>"
|
16 |
+
],
|
17 |
+
"eos_token": {
|
18 |
+
"content": "<|im_end|>",
|
19 |
+
"lstrip": false,
|
20 |
+
"normalized": false,
|
21 |
+
"rstrip": false,
|
22 |
+
"single_word": false
|
23 |
+
},
|
24 |
+
"pad_token": {
|
25 |
+
"content": "<|vision_pad|>",
|
26 |
+
"lstrip": false,
|
27 |
+
"normalized": false,
|
28 |
+
"rstrip": false,
|
29 |
+
"single_word": false
|
30 |
+
}
|
31 |
+
}
|
tokenizer.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4
|
3 |
+
size 11422654
|
tokenizer_config.json
ADDED
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_bos_token": false,
|
3 |
+
"add_prefix_space": false,
|
4 |
+
"added_tokens_decoder": {
|
5 |
+
"151643": {
|
6 |
+
"content": "<|endoftext|>",
|
7 |
+
"lstrip": false,
|
8 |
+
"normalized": false,
|
9 |
+
"rstrip": false,
|
10 |
+
"single_word": false,
|
11 |
+
"special": true
|
12 |
+
},
|
13 |
+
"151644": {
|
14 |
+
"content": "<|im_start|>",
|
15 |
+
"lstrip": false,
|
16 |
+
"normalized": false,
|
17 |
+
"rstrip": false,
|
18 |
+
"single_word": false,
|
19 |
+
"special": true
|
20 |
+
},
|
21 |
+
"151645": {
|
22 |
+
"content": "<|im_end|>",
|
23 |
+
"lstrip": false,
|
24 |
+
"normalized": false,
|
25 |
+
"rstrip": false,
|
26 |
+
"single_word": false,
|
27 |
+
"special": true
|
28 |
+
},
|
29 |
+
"151646": {
|
30 |
+
"content": "<|object_ref_start|>",
|
31 |
+
"lstrip": false,
|
32 |
+
"normalized": false,
|
33 |
+
"rstrip": false,
|
34 |
+
"single_word": false,
|
35 |
+
"special": true
|
36 |
+
},
|
37 |
+
"151647": {
|
38 |
+
"content": "<|object_ref_end|>",
|
39 |
+
"lstrip": false,
|
40 |
+
"normalized": false,
|
41 |
+
"rstrip": false,
|
42 |
+
"single_word": false,
|
43 |
+
"special": true
|
44 |
+
},
|
45 |
+
"151648": {
|
46 |
+
"content": "<|box_start|>",
|
47 |
+
"lstrip": false,
|
48 |
+
"normalized": false,
|
49 |
+
"rstrip": false,
|
50 |
+
"single_word": false,
|
51 |
+
"special": true
|
52 |
+
},
|
53 |
+
"151649": {
|
54 |
+
"content": "<|box_end|>",
|
55 |
+
"lstrip": false,
|
56 |
+
"normalized": false,
|
57 |
+
"rstrip": false,
|
58 |
+
"single_word": false,
|
59 |
+
"special": true
|
60 |
+
},
|
61 |
+
"151650": {
|
62 |
+
"content": "<|quad_start|>",
|
63 |
+
"lstrip": false,
|
64 |
+
"normalized": false,
|
65 |
+
"rstrip": false,
|
66 |
+
"single_word": false,
|
67 |
+
"special": true
|
68 |
+
},
|
69 |
+
"151651": {
|
70 |
+
"content": "<|quad_end|>",
|
71 |
+
"lstrip": false,
|
72 |
+
"normalized": false,
|
73 |
+
"rstrip": false,
|
74 |
+
"single_word": false,
|
75 |
+
"special": true
|
76 |
+
},
|
77 |
+
"151652": {
|
78 |
+
"content": "<|vision_start|>",
|
79 |
+
"lstrip": false,
|
80 |
+
"normalized": false,
|
81 |
+
"rstrip": false,
|
82 |
+
"single_word": false,
|
83 |
+
"special": true
|
84 |
+
},
|
85 |
+
"151653": {
|
86 |
+
"content": "<|vision_end|>",
|
87 |
+
"lstrip": false,
|
88 |
+
"normalized": false,
|
89 |
+
"rstrip": false,
|
90 |
+
"single_word": false,
|
91 |
+
"special": true
|
92 |
+
},
|
93 |
+
"151654": {
|
94 |
+
"content": "<|vision_pad|>",
|
95 |
+
"lstrip": false,
|
96 |
+
"normalized": false,
|
97 |
+
"rstrip": false,
|
98 |
+
"single_word": false,
|
99 |
+
"special": true
|
100 |
+
},
|
101 |
+
"151655": {
|
102 |
+
"content": "<|image_pad|>",
|
103 |
+
"lstrip": false,
|
104 |
+
"normalized": false,
|
105 |
+
"rstrip": false,
|
106 |
+
"single_word": false,
|
107 |
+
"special": true
|
108 |
+
},
|
109 |
+
"151656": {
|
110 |
+
"content": "<|video_pad|>",
|
111 |
+
"lstrip": false,
|
112 |
+
"normalized": false,
|
113 |
+
"rstrip": false,
|
114 |
+
"single_word": false,
|
115 |
+
"special": true
|
116 |
+
},
|
117 |
+
"151657": {
|
118 |
+
"content": "<tool_call>",
|
119 |
+
"lstrip": false,
|
120 |
+
"normalized": false,
|
121 |
+
"rstrip": false,
|
122 |
+
"single_word": false,
|
123 |
+
"special": false
|
124 |
+
},
|
125 |
+
"151658": {
|
126 |
+
"content": "</tool_call>",
|
127 |
+
"lstrip": false,
|
128 |
+
"normalized": false,
|
129 |
+
"rstrip": false,
|
130 |
+
"single_word": false,
|
131 |
+
"special": false
|
132 |
+
},
|
133 |
+
"151659": {
|
134 |
+
"content": "<|fim_prefix|>",
|
135 |
+
"lstrip": false,
|
136 |
+
"normalized": false,
|
137 |
+
"rstrip": false,
|
138 |
+
"single_word": false,
|
139 |
+
"special": false
|
140 |
+
},
|
141 |
+
"151660": {
|
142 |
+
"content": "<|fim_middle|>",
|
143 |
+
"lstrip": false,
|
144 |
+
"normalized": false,
|
145 |
+
"rstrip": false,
|
146 |
+
"single_word": false,
|
147 |
+
"special": false
|
148 |
+
},
|
149 |
+
"151661": {
|
150 |
+
"content": "<|fim_suffix|>",
|
151 |
+
"lstrip": false,
|
152 |
+
"normalized": false,
|
153 |
+
"rstrip": false,
|
154 |
+
"single_word": false,
|
155 |
+
"special": false
|
156 |
+
},
|
157 |
+
"151662": {
|
158 |
+
"content": "<|fim_pad|>",
|
159 |
+
"lstrip": false,
|
160 |
+
"normalized": false,
|
161 |
+
"rstrip": false,
|
162 |
+
"single_word": false,
|
163 |
+
"special": false
|
164 |
+
},
|
165 |
+
"151663": {
|
166 |
+
"content": "<|repo_name|>",
|
167 |
+
"lstrip": false,
|
168 |
+
"normalized": false,
|
169 |
+
"rstrip": false,
|
170 |
+
"single_word": false,
|
171 |
+
"special": false
|
172 |
+
},
|
173 |
+
"151664": {
|
174 |
+
"content": "<|file_sep|>",
|
175 |
+
"lstrip": false,
|
176 |
+
"normalized": false,
|
177 |
+
"rstrip": false,
|
178 |
+
"single_word": false,
|
179 |
+
"special": false
|
180 |
+
},
|
181 |
+
"151665": {
|
182 |
+
"content": "<tool_response>",
|
183 |
+
"lstrip": false,
|
184 |
+
"normalized": false,
|
185 |
+
"rstrip": false,
|
186 |
+
"single_word": false,
|
187 |
+
"special": false
|
188 |
+
},
|
189 |
+
"151666": {
|
190 |
+
"content": "</tool_response>",
|
191 |
+
"lstrip": false,
|
192 |
+
"normalized": false,
|
193 |
+
"rstrip": false,
|
194 |
+
"single_word": false,
|
195 |
+
"special": false
|
196 |
+
},
|
197 |
+
"151667": {
|
198 |
+
"content": "<think>",
|
199 |
+
"lstrip": false,
|
200 |
+
"normalized": false,
|
201 |
+
"rstrip": false,
|
202 |
+
"single_word": false,
|
203 |
+
"special": false
|
204 |
+
},
|
205 |
+
"151668": {
|
206 |
+
"content": "</think>",
|
207 |
+
"lstrip": false,
|
208 |
+
"normalized": false,
|
209 |
+
"rstrip": false,
|
210 |
+
"single_word": false,
|
211 |
+
"special": false
|
212 |
+
}
|
213 |
+
},
|
214 |
+
"additional_special_tokens": [
|
215 |
+
"<|im_start|>",
|
216 |
+
"<|im_end|>",
|
217 |
+
"<|object_ref_start|>",
|
218 |
+
"<|object_ref_end|>",
|
219 |
+
"<|box_start|>",
|
220 |
+
"<|box_end|>",
|
221 |
+
"<|quad_start|>",
|
222 |
+
"<|quad_end|>",
|
223 |
+
"<|vision_start|>",
|
224 |
+
"<|vision_end|>",
|
225 |
+
"<|vision_pad|>",
|
226 |
+
"<|image_pad|>",
|
227 |
+
"<|video_pad|>"
|
228 |
+
],
|
229 |
+
"bos_token": null,
|
230 |
+
"clean_up_tokenization_spaces": false,
|
231 |
+
"eos_token": "<|im_end|>",
|
232 |
+
"errors": "replace",
|
233 |
+
"extra_special_tokens": {},
|
234 |
+
"model_max_length": 40960,
|
235 |
+
"pad_token": "<|vision_pad|>",
|
236 |
+
"padding_side": "right",
|
237 |
+
"split_special_tokens": false,
|
238 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
239 |
+
"unk_token": null
|
240 |
+
}
|
vocab.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|