puretensor commited on
Commit
f85db27
·
verified ·
1 Parent(s): b1451d7

NVFP4 (GPTQ, W4A4) quantization of microsoft/Aion-1.0-Instruct-2.3B

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ 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
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) Microsoft Corporation.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ license_link: https://huggingface.co/microsoft/Aion-1.0-Instruct-2.3B/blob/main/LICENSE
4
+ base_model: microsoft/Aion-1.0-Instruct-2.3B
5
+ base_model_relation: quantized
6
+ library_name: transformers
7
+ pipeline_tag: text-generation
8
+ tags:
9
+ - nvfp4
10
+ - 4-bit
11
+ - compressed-tensors
12
+ - llm-compressor
13
+ - gptq
14
+ - quantized
15
+ - custom_code
16
+ ---
17
+
18
+ # Aion-1.0-Instruct-2.3B NVFP4 (GPTQ)
19
+
20
+ NVFP4 quantization of [microsoft/Aion-1.0-Instruct-2.3B](https://huggingface.co/microsoft/Aion-1.0-Instruct-2.3B), made by PureTensor from the official BF16 weights. Weights and activations are both 4-bit (W4A4). The file is 1.88 GB against 4.58 GB for BF16.
21
+
22
+ This is a test release. It is not affiliated with or endorsed by Microsoft.
23
+
24
+ **Read this first:** a 2.3B model loses measurable quality at 4 bits. On our harness this checkpoint is 2.1 points below BF16 on MMLU and 6.1 points below on GSM8K, and both gaps are statistically significant. The numbers are below.
25
+
26
+ ## What was done
27
+
28
+ | | |
29
+ |---|---|
30
+ | Source | `microsoft/Aion-1.0-Instruct-2.3B`, BF16, `model.safetensors` sha256 `6c779881...6984e` |
31
+ | Format | compressed-tensors `nvfp4-pack-quantized`: 4-bit E2M1 values, one FP8 E4M3 scale per group of 16, one FP32 scale per tensor |
32
+ | Quantized | every `Linear` layer in the 28 transformer blocks (weights, plus 4-bit input activations) |
33
+ | Kept in BF16 | token embeddings and the tied output head, all norms |
34
+ | Method | GPTQ (`block_size` 128, `dampening_frac` 0.01, `actorder` static) |
35
+ | Calibration | 512 samples of `mlabonne/open-perfectblend`, up to 2,048 tokens each |
36
+ | Tools | llm-compressor 0.15.0, compressed-tensors 0.20.1, transformers 5.21.0, torch 2.14.1 |
37
+
38
+ Recipe:
39
+
40
+ ```python
41
+ from llmcompressor import oneshot
42
+ from llmcompressor.modifiers.quantization import GPTQModifier
43
+
44
+ recipe = GPTQModifier(targets="Linear", scheme="NVFP4", ignore=["lm_head"])
45
+ oneshot(
46
+ model=model, processor=tokenizer, recipe=recipe,
47
+ dataset="perfectblend", splits="train[:512]",
48
+ num_calibration_samples=512, max_seq_length=2048,
49
+ trust_remote_code_model=True,
50
+ )
51
+ model.save_pretrained(out_dir, save_compressed=True)
52
+ ```
53
+
54
+ ## Measured quality
55
+
56
+ Everything below was measured by us in one harness, with the BF16 model as the reference. The saved checkpoint was reloaded from disk and matched the in-memory quantized model exactly (identical logits on 4,096 tokens).
57
+
58
+ | | BF16 | This checkpoint | Change |
59
+ |---|---:|---:|---:|
60
+ | MMLU, accuracy (14,042 questions) | 54.88 | 52.74 | -2.14 |
61
+ | GSM8K, exact match (1,319 problems) | 61.26 | 55.12 | -6.14 |
62
+ | WikiText-2 perplexity (131,072 tokens) | 11.39 | 12.28 | +0.89 |
63
+
64
+ Agreement with BF16, token by token:
65
+
66
+ | Text | Tokens | Mean KL divergence | 99th percentile KL | Same top token |
67
+ |---|---:|---:|---:|---:|
68
+ | WikiText-2 test | 131,072 | 0.095 | 0.71 | 84.7% |
69
+ | Chat (`HuggingFaceH4/ultrachat_200k`, `test_sft`, 256 conversations) | 224,534 | 0.077 | 0.58 | 86.7% |
70
+
71
+ Paired McNemar tests on per-question correctness against BF16: MMLU 1,058 questions lost and 758 gained (p = 2e-12); GSM8K 166 lost and 85 gained (p = 4e-7).
72
+
73
+ Details:
74
+ - MMLU and GSM8K use the default `mmlu` and `gsm8k` task configurations of lm-evaluation-harness 0.4.13, without a chat template. GSM8K is the flexible-extract score. Our BF16 MMLU (54.88) is close to the 55.15 on the base model card; our GSM8K setup differs from theirs, so compare the two columns above with each other and not with the base card.
75
+ - KL divergence is computed on the full next-token distribution, teacher-forced, in windows of 1,024 tokens. The chat set uses the model's chat template.
76
+
77
+ ### Why GPTQ
78
+
79
+ We built five NVFP4 variants from the same weights and scored them the same way. GPTQ was best on every metric, including against the two variants that leave activations at 16 bits.
80
+
81
+ | Variant | Activations | MMLU | GSM8K | KL, wiki | KL, chat |
82
+ |---|---|---:|---:|---:|---:|
83
+ | BF16 reference | 16-bit | 54.88 | 61.26 | 0 | 0 |
84
+ | **GPTQ (this checkpoint)** | 4-bit | **52.74** | **55.12** | **0.095** | **0.077** |
85
+ | Round-to-nearest | 4-bit | 50.55 | 45.56 | 0.175 | 0.327 |
86
+ | Expanded MSE scales | 4-bit | 50.67 | 47.31 | 0.148 | 0.311 |
87
+ | Round-to-nearest, weights only | 16-bit | 52.65 | 50.34 | 0.098 | 0.281 |
88
+ | Expanded MSE scales, weights only | 16-bit | 52.32 | 53.37 | 0.098 | 0.263 |
89
+
90
+ One caution on the chat column: GPTQ is calibrated on chat-style data, so part of its lead there may come from that. The WikiText column is unrelated to the calibration data and GPTQ still leads.
91
+
92
+ ## Usage
93
+
94
+ ```python
95
+ import torch
96
+ from transformers import AutoModelForCausalLM, AutoTokenizer
97
+
98
+ repo = "puretensor/Aion-1.0-Instruct-2.3B-NVFP4"
99
+ tok = AutoTokenizer.from_pretrained(repo, trust_remote_code=True)
100
+ model = AutoModelForCausalLM.from_pretrained(
101
+ repo, trust_remote_code=True, dtype=torch.bfloat16
102
+ ).to("cuda")
103
+
104
+ msgs = [{"role": "user", "content": "Summarise the water cycle in two sentences."}]
105
+ ids = tok.apply_chat_template(msgs, add_generation_prompt=True, return_tensors="pt", return_dict=True).to("cuda")
106
+ out = model.generate(**ids, max_new_tokens=128)
107
+ print(tok.decode(out[0, ids["input_ids"].shape[1]:], skip_special_tokens=True))
108
+ ```
109
+
110
+ Requires `compressed-tensors` (`pip install compressed-tensors`) and `trust_remote_code=True`, as the base model does.
111
+
112
+ ## Limitations
113
+
114
+ - **No native FP4 serving yet.** This architecture has no vLLM implementation at the time of writing (2026-11-20). In Transformers the 4-bit arithmetic is emulated, so this checkpoint gives the quality of NVFP4 but not its speed. All numbers above were measured that way.
115
+ - **Load in BF16.** A float32 load failed in our test with a dtype mismatch. BF16 on CPU works but is slow.
116
+ - **Quality loss is real at this size.** See the tables. If you need the base model's quality, use BF16.
117
+ - English-language benchmarks only; no safety, multilingual, or long-context evaluation was run on the quantized model.
118
+
119
+ ## License
120
+
121
+ MIT, as the base model. The original `LICENSE` is included. Changes from the base release: the `Linear` weights are quantized to NVFP4 and stored packed, activation quantization parameters are added, and `config.json` gains a `quantization_config` block.
chat_template.jinja ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- set _reserved_control_tokens = ['<|system|>', '<|user|>', '<|assistant|>', '<|end|>', '<|endofprompt|>', '<|tool|>', '<|/tool|>', '<|tool_call|>', '<|/tool_call|>', '<|tool_response|>'] %}
2
+ {%- if model_identity is not defined %}
3
+ {%- set model_identity = "You are Aion Instruct, a large language model trained by Microsoft." %}
4
+ {%- endif %}
5
+ {%- if knowledge_cutoff is not defined or not knowledge_cutoff %}
6
+ {%- set knowledge_cutoff = "2025-12" %}
7
+ {%- endif %}
8
+ {%- if messages and messages[0].role == 'system' %}
9
+ {%- set start_index = 1 %}
10
+ {%- else %}
11
+ {%- set start_index = 0 %}
12
+ {%- endif %}
13
+ {{- '<|system|>' + model_identity }}
14
+ {{- '\nKnowledge cutoff: ' + knowledge_cutoff }}
15
+ {%- if current_date is defined and current_date %}
16
+ {{- '\nCurrent date: ' + current_date }}
17
+ {%- else %}
18
+ {{- '\nCurrent date: ' + strftime_now('%Y-%m-%d') }}
19
+ {%- endif %}
20
+ {%- if messages and messages[0].role == 'system' %}
21
+ {%- if messages[0].content is string %}
22
+ {%- set _sys_content = messages[0].content %}
23
+ {%- else %}
24
+ {%- set _sys_content = '' %}
25
+ {%- endif %}
26
+ {%- for _t in _reserved_control_tokens %}
27
+ {%- if _sys_content and _t in _sys_content %}
28
+ {{- raise_exception("aion chat template: content of the leading 'system' message contains reserved control token " ~ _t ~ "; strip chat control tokens from the data.") }}
29
+ {%- endif %}
30
+ {%- endfor %}
31
+ {{- '\n\n' + _sys_content }}
32
+ {%- endif %}
33
+ {%- if tools %}
34
+ {{- '\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nThe available tools are provided as JSON between <|tool|> and <|/tool|> tokens:\n' }}
35
+ {{- '<|tool|>' }}
36
+ {{- tools | tojson }}
37
+ {{- '<|/tool|>\n\nFor each function call, respond with a single <|tool_call|>{\"name\": \"<function-name>\", \"arguments\": <json-args>}<|/tool_call|> block.\n' }}
38
+ {%- endif %}
39
+ {{- '<|end|>' }}
40
+ {%- set _ns = namespace(pending_tool_call=false) %}
41
+ {%- for message in messages[start_index:] %}
42
+ {%- if message.content is string %}
43
+ {%- set content = message.content %}
44
+ {%- else %}
45
+ {%- set content = '' %}
46
+ {%- endif %}
47
+ {%- for _t in _reserved_control_tokens %}
48
+ {%- if content and _t in content %}
49
+ {{- raise_exception("aion chat template: content of a '" ~ message.role ~ "' message contains reserved control token " ~ _t ~ "; strip chat control tokens from the data.") }}
50
+ {%- endif %}
51
+ {%- endfor %}
52
+ {%- if message.role == 'user' %}
53
+ {{- '<|user|>' + content + '<|end|>' }}
54
+ {%- set _ns.pending_tool_call = false %}
55
+ {%- elif message.role == 'assistant' %}
56
+ {{- '<|assistant|>' }}
57
+ {%- generation %}
58
+ {{- content }}
59
+ {%- if message.tool_calls %}
60
+ {%- for tool_call in message.tool_calls %}
61
+ {%- if tool_call.function %}
62
+ {%- set tc = tool_call.function %}
63
+ {%- else %}
64
+ {%- set tc = tool_call %}
65
+ {%- endif %}
66
+ {{- '<|tool_call|>' }}
67
+ {{- '{\"name\": \"' ~ tc.name ~ '\", \"arguments\": ' }}
68
+ {%- if tc.arguments is string %}
69
+ {{- tc.arguments }}
70
+ {%- else %}
71
+ {{- tc.arguments | tojson }}
72
+ {%- endif %}
73
+ {{- '}' }}
74
+ {{- '<|/tool_call|>' }}
75
+ {%- endfor %}
76
+ {%- endif %}
77
+ {#- EVERY assistant turn -- including the conversation-final one -- closes on
78
+ <|end|> (200020), which IS the model's emitted eos (Phi-4 / Phi-4-reasoning
79
+ single-terminator scheme: <|im_end|> ends every turn AND is the eos, with NO
80
+ separate document terminator). Training on it teaches the model to STOP. The IFT
81
+ assistant-only loss trains this closing token. Packing isolates
82
+ conversations via reset position_ids (no distinct terminal token needed). #}
83
+ {{- '<|end|>' }}
84
+ {%- endgeneration %}
85
+ {%- if message.tool_calls %}
86
+ {%- set _ns.pending_tool_call = true %}
87
+ {%- else %}
88
+ {%- set _ns.pending_tool_call = false %}
89
+ {%- endif %}
90
+ {%- elif message.role == 'tool' %}
91
+ {%- if not _ns.pending_tool_call %}
92
+ {{- raise_exception("aion chat template: a 'tool' message has no preceding assistant tool_call.") }}
93
+ {%- endif %}
94
+ {%- if loop.first or (messages[loop.index0 + start_index - 1].role != 'tool') %}
95
+ {{- '<|user|>' }}
96
+ {%- endif %}
97
+ {{- '<|tool_response|>' }}
98
+ {{- content }}
99
+ {%- if loop.last or (messages[loop.index0 + start_index + 1].role != 'tool') %}
100
+ <|end|>
101
+ {%- endif %}
102
+ {%- elif message.role == 'system' and (start_index + loop.index0) != 0 %}
103
+ {%- if content | trim %}
104
+ {{- '<|system|>' + content + '<|end|>' }}
105
+ {%- endif %}
106
+ {%- endif %}
107
+ {%- endfor %}
108
+ {%- if add_generation_prompt %}
109
+ {{- '<|assistant|>' }}
110
+ {%- else %}
111
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "AionInstructForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_aion_instruct.AionInstructConfig",
9
+ "AutoModel": "modeling_aion_instruct.AionInstructModel",
10
+ "AutoModelForCausalLM": "modeling_aion_instruct.AionInstructForCausalLM"
11
+ },
12
+ "bos_token_id": 199999,
13
+ "dtype": "bfloat16",
14
+ "eos_token_id": 200020,
15
+ "head_dim": 128,
16
+ "hidden_act": "silu",
17
+ "hidden_size": 2048,
18
+ "initializer_range": 0.02,
19
+ "intermediate_size": 8192,
20
+ "layer_types": [
21
+ "sliding_attention",
22
+ "sliding_attention",
23
+ "full_attention",
24
+ "full_attention",
25
+ "full_attention",
26
+ "sliding_attention",
27
+ "sliding_attention",
28
+ "sliding_attention",
29
+ "sliding_attention",
30
+ "full_attention",
31
+ "sliding_attention",
32
+ "sliding_attention",
33
+ "sliding_attention",
34
+ "full_attention",
35
+ "sliding_attention",
36
+ "full_attention",
37
+ "full_attention",
38
+ "sliding_attention",
39
+ "sliding_attention",
40
+ "sliding_attention",
41
+ "sliding_attention",
42
+ "sliding_attention",
43
+ "sliding_attention",
44
+ "sliding_attention",
45
+ "sliding_attention",
46
+ "sliding_attention",
47
+ "sliding_attention",
48
+ "sliding_attention"
49
+ ],
50
+ "max_position_embeddings": 32768,
51
+ "model_type": "aion_instruct",
52
+ "num_attention_heads": 24,
53
+ "num_hidden_layers": 28,
54
+ "num_key_value_heads": 8,
55
+ "pad_token_id": 199999,
56
+ "quantization_config": {
57
+ "config_groups": {
58
+ "group_0": {
59
+ "format": "nvfp4-pack-quantized",
60
+ "input_activations": {
61
+ "dynamic": "local",
62
+ "group_size": 16,
63
+ "num_bits": 4,
64
+ "observer": "static_minmax",
65
+ "scale_dtype": "torch.float8_e4m3fn",
66
+ "strategy": "tensor_group",
67
+ "symmetric": true,
68
+ "type": "float"
69
+ },
70
+ "output_activations": null,
71
+ "targets": [
72
+ "Linear"
73
+ ],
74
+ "weights": {
75
+ "actorder": "static",
76
+ "dynamic": false,
77
+ "group_size": 16,
78
+ "num_bits": 4,
79
+ "observer": "memoryless_minmax",
80
+ "scale_dtype": "torch.float8_e4m3fn",
81
+ "strategy": "tensor_group",
82
+ "symmetric": true,
83
+ "type": "float"
84
+ }
85
+ }
86
+ },
87
+ "format": "nvfp4-pack-quantized",
88
+ "global_compression_ratio": null,
89
+ "ignore": [
90
+ "lm_head"
91
+ ],
92
+ "kv_cache_scheme": null,
93
+ "moe_sparsity_config": null,
94
+ "quant_method": "compressed-tensors",
95
+ "quantization_status": "compressed",
96
+ "sparsity_config": {},
97
+ "transform_config": {},
98
+ "version": "0.20.1"
99
+ },
100
+ "rms_norm_eps": 1e-06,
101
+ "rope_parameters": {
102
+ "full_attention": {
103
+ "beta_fast": 32.0,
104
+ "beta_slow": 1.0,
105
+ "factor": 16.0,
106
+ "original_max_position_embeddings": 2048,
107
+ "rope_theta": 32000,
108
+ "rope_type": "yarn"
109
+ },
110
+ "sliding_attention": {
111
+ "rope_theta": 32000,
112
+ "rope_type": "default"
113
+ }
114
+ },
115
+ "sliding_window": 2048,
116
+ "tie_word_embeddings": true,
117
+ "transformers_version": "5.9.0",
118
+ "use_cache": true,
119
+ "vocab_size": 200029
120
+ }
configuration_aion_instruct.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2026 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the MIT License.
5
+ #
6
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ # of this software and associated documentation files (the "Software"), to deal
8
+ # in the Software without restriction, including without limitation the rights
9
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ # copies of the Software, and to permit persons to whom the Software is
11
+ # furnished to do so, subject to the following conditions:
12
+ #
13
+ # The above copyright notice and this permission notice shall be included in all
14
+ # copies or substantial portions of the Software.
15
+ #
16
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ # SOFTWARE.
23
+ """AionInstruct model configuration"""
24
+
25
+ from huggingface_hub.dataclasses import strict
26
+ from transformers.configuration_utils import PreTrainedConfig
27
+
28
+ ATTENTION_LAYER_TYPES = ("full_attention", "sliding_attention")
29
+
30
+
31
+ @strict
32
+ class AionInstructConfig(PreTrainedConfig):
33
+ r"""
34
+ This is the configuration class to store the configuration of an [`AionInstructModel`]. It is used to instantiate
35
+ an AionInstruct model according to the specified arguments, defining the model architecture. The defaults
36
+ correspond to the 2.3B-parameter Aion 1.1 Instruct model, except for `layer_types`, which defaults to full
37
+ attention in every layer.
38
+
39
+ AionInstruct is a decoder-only Transformer with grouped-query attention, RMSNorm on every query and key head,
40
+ a SwiGLU MLP, tied input/output embeddings, and a per-layer choice between full and sliding-window attention.
41
+ Each attention type has its own rotary position embedding parameters: Aion 1.1 extends the context of its
42
+ full-attention layers with YaRN and keeps un-scaled RoPE in its sliding-window layers.
43
+
44
+ Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
45
+ documentation from [`PreTrainedConfig`] for more information.
46
+
47
+ Args:
48
+ vocab_size (`int`, *optional*, defaults to 200029):
49
+ Vocabulary size of the model.
50
+ hidden_size (`int`, *optional*, defaults to 2048):
51
+ Dimension of the hidden representations.
52
+ intermediate_size (`int`, *optional*, defaults to 8192):
53
+ Dimension of the MLP representations.
54
+ num_hidden_layers (`int`, *optional*, defaults to 28):
55
+ Number of decoder layers.
56
+ num_attention_heads (`int`, *optional*, defaults to 24):
57
+ Number of query heads in each attention layer.
58
+ num_key_value_heads (`int`, *optional*, defaults to 8):
59
+ Number of key/value heads for grouped-query attention. `None` means `num_attention_heads`.
60
+ head_dim (`int`, *optional*, defaults to 128):
61
+ Dimension of each attention head. It is independent of `hidden_size // num_attention_heads`.
62
+ hidden_act (`str`, *optional*, defaults to `"silu"`):
63
+ Activation of the gated MLP.
64
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
65
+ Maximum sequence length the model supports.
66
+ initializer_range (`float`, *optional*, defaults to 0.02):
67
+ Standard deviation of the normal initializer of the weight matrices.
68
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
69
+ Epsilon of the RMS normalization layers.
70
+ use_cache (`bool`, *optional*, defaults to `True`):
71
+ Whether the model returns the last key/value states.
72
+ tie_word_embeddings (`bool`, *optional*, defaults to `True`):
73
+ Whether the output projection shares the input embedding matrix.
74
+ rope_parameters (`dict`, *optional*):
75
+ Rotary position embedding parameters for each attention type: a dictionary whose keys are the layer
76
+ types in `layer_types` and whose values are [`~modeling_rope_utils.RopeParameters`] dictionaries. A
77
+ single, un-nested dictionary applies to every layer type. A layer type without parameters uses un-scaled
78
+ RoPE. Defaults to YaRN (factor 16 over an original context of 2048 positions, base 32000) for
79
+ full-attention layers and un-scaled RoPE with the same base for sliding-window layers.
80
+ attention_bias (`bool`, *optional*, defaults to `False`):
81
+ Whether the query, key, value and output projections have a bias.
82
+ attention_dropout (`float`, *optional*, defaults to 0.0):
83
+ Dropout ratio of the attention probabilities.
84
+ sliding_window (`int`, *optional*, defaults to 2048):
85
+ Attention window of the `"sliding_attention"` layers. Unused by `"full_attention"` layers.
86
+ layer_types (`list[str]`, *optional*):
87
+ Attention type of each layer, `"full_attention"` or `"sliding_attention"`. Defaults to full attention in
88
+ every layer.
89
+ pad_token_id (`int`, *optional*):
90
+ Padding token id.
91
+ bos_token_id (`int`, *optional*):
92
+ Beginning of stream token id.
93
+ eos_token_id (`int` or `list[int]`, *optional*):
94
+ End of stream token id(s).
95
+
96
+ ```python
97
+ >>> from transformers import AionInstructConfig, AionInstructModel
98
+
99
+ >>> # Initializing an AionInstruct configuration
100
+ >>> configuration = AionInstructConfig()
101
+
102
+ >>> # Initializing a model (with random weights) from the configuration
103
+ >>> model = AionInstructModel(configuration)
104
+
105
+ >>> # Accessing the model configuration
106
+ >>> configuration = model.config
107
+ ```"""
108
+
109
+ model_type = "aion_instruct"
110
+ keys_to_ignore_at_inference = ["past_key_values"]
111
+ default_theta = 32_000.0
112
+
113
+ base_model_tp_plan = {
114
+ "layers.*.self_attn.q_proj": "colwise",
115
+ "layers.*.self_attn.k_proj": "colwise",
116
+ "layers.*.self_attn.v_proj": "colwise",
117
+ "layers.*.self_attn.q_norm": "replicated_with_grad_allreduce",
118
+ "layers.*.self_attn.k_norm": "replicated_with_grad_allreduce",
119
+ "layers.*.self_attn.o_proj": "rowwise",
120
+ "layers.*.mlp.gate_proj": "colwise",
121
+ "layers.*.mlp.up_proj": "colwise",
122
+ "layers.*.mlp.down_proj": "rowwise",
123
+ }
124
+ base_model_pp_plan = {
125
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
126
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
127
+ "norm": (["hidden_states"], ["hidden_states"]),
128
+ }
129
+
130
+ vocab_size: int = 200029
131
+ hidden_size: int = 2048
132
+ intermediate_size: int = 8192
133
+ num_hidden_layers: int = 28
134
+ num_attention_heads: int = 24
135
+ num_key_value_heads: int | None = 8
136
+ head_dim: int = 128
137
+ hidden_act: str = "silu"
138
+ max_position_embeddings: int = 32768
139
+ initializer_range: float = 0.02
140
+ rms_norm_eps: float = 1e-6
141
+ use_cache: bool = True
142
+ tie_word_embeddings: bool = True
143
+ rope_parameters: dict | None = None
144
+ attention_bias: bool = False
145
+ attention_dropout: float | int = 0.0
146
+ sliding_window: int | None = 2048
147
+ layer_types: list[str] | None = None
148
+ pad_token_id: int | None = None
149
+ bos_token_id: int | None = None
150
+ eos_token_id: int | list[int] | None = None
151
+
152
+ def __post_init__(self, **kwargs):
153
+ if self.num_key_value_heads is None:
154
+ self.num_key_value_heads = self.num_attention_heads
155
+ if self.layer_types is None:
156
+ self.layer_types = ["full_attention"] * self.num_hidden_layers
157
+ super().__post_init__(**kwargs)
158
+
159
+ def convert_rope_params_to_dict(self, **kwargs):
160
+ rope_scaling = kwargs.pop("rope_scaling", None)
161
+ rope_theta = kwargs.pop("rope_theta", self.default_theta)
162
+ rope_parameters = rope_scaling or self.rope_parameters
163
+ if rope_parameters is None:
164
+ rope_parameters = {
165
+ "full_attention": {
166
+ "rope_type": "yarn",
167
+ "factor": 16.0,
168
+ "original_max_position_embeddings": 2048,
169
+ "beta_fast": 32.0,
170
+ "beta_slow": 1.0,
171
+ },
172
+ "sliding_attention": {"rope_type": "default"},
173
+ }
174
+ elif set(rope_parameters).isdisjoint(ATTENTION_LAYER_TYPES):
175
+ rope_parameters = dict.fromkeys(ATTENTION_LAYER_TYPES, rope_parameters)
176
+
177
+ # Keep exactly the layer types in use: transformers recognizes per-layer-type parameters by their keys.
178
+ self.rope_parameters = {}
179
+ for layer_type in sorted(set(self.layer_types)):
180
+ layer_rope_parameters = dict(rope_parameters.get(layer_type) or {"rope_type": "default"})
181
+ layer_rope_parameters.setdefault("rope_theta", rope_theta)
182
+ self.rope_parameters[layer_type] = layer_rope_parameters
183
+ self.standardize_rope_params()
184
+ return kwargs
185
+
186
+ def validate_architecture(self):
187
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
188
+ super().validate_architecture()
189
+ if "sliding_attention" in self.layer_types and self.sliding_window is None:
190
+ raise ValueError("`sliding_window` must be set when `layer_types` contains sliding-attention layers.")
191
+ if self.num_attention_heads % self.num_key_value_heads != 0:
192
+ raise ValueError(
193
+ f"`num_attention_heads` ({self.num_attention_heads}) must be a multiple of `num_key_value_heads` "
194
+ f"({self.num_key_value_heads})."
195
+ )
196
+
197
+ def validate_layer_type(self):
198
+ """Part of `@strict`-powered validation. Restricts `layer_types` to `ATTENTION_LAYER_TYPES`."""
199
+ super().validate_layer_type()
200
+ if unsupported := set(self.layer_types) - set(ATTENTION_LAYER_TYPES):
201
+ raise ValueError(f"`layer_types` entries must be in {ATTENTION_LAYER_TYPES}, got {sorted(unsupported)}.")
202
+
203
+
204
+ __all__ = ["AionInstructConfig"]
generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 199999,
4
+ "eos_token_id": [
5
+ 200020,
6
+ 199999
7
+ ],
8
+ "output_attentions": false,
9
+ "output_hidden_states": false,
10
+ "pad_token_id": 199999,
11
+ "transformers_version": "5.21.0",
12
+ "use_cache": true
13
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:47383de6bd66f9ebe3c54ebf5b53ca43fc7fbca5622b39212f24b4d706923097
3
+ size 1876634776
modeling_aion_instruct.py ADDED
@@ -0,0 +1,527 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2026 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the MIT License.
5
+ #
6
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ # of this software and associated documentation files (the "Software"), to deal
8
+ # in the Software without restriction, including without limitation the rights
9
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ # copies of the Software, and to permit persons to whom the Software is
11
+ # furnished to do so, subject to the following conditions:
12
+ #
13
+ # The above copyright notice and this permission notice shall be included in all
14
+ # copies or substantial portions of the Software.
15
+ #
16
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ # SOFTWARE.
23
+ """PyTorch AionInstruct model."""
24
+
25
+ from collections.abc import Callable
26
+
27
+ import torch
28
+ from torch import nn
29
+
30
+ from transformers import initialization as init
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache
33
+ from transformers.generation import GenerationMixin
34
+ from transformers.integrations import use_kernel_forward_from_hub
35
+ from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
36
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
37
+ from transformers.modeling_layers import GradientCheckpointingLayer
38
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
39
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
40
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
41
+ from transformers.processing_utils import Unpack
42
+ from transformers.utils import TransformersKwargs, can_return_tuple
43
+ from transformers.utils.generic import maybe_autocast, merge_with_config_defaults
44
+ from transformers.utils.output_capturing import capture_outputs
45
+
46
+ from .configuration_aion_instruct import AionInstructConfig
47
+
48
+
49
+ @use_kernel_forward_from_hub("RMSNorm")
50
+ class AionInstructRMSNorm(nn.Module):
51
+ def __init__(self, hidden_size, eps: float = 1e-6) -> None:
52
+ super().__init__()
53
+ self.weight = nn.Parameter(torch.ones(hidden_size))
54
+ self.variance_epsilon = eps
55
+
56
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
57
+ input_dtype = hidden_states.dtype
58
+ hidden_states = hidden_states.to(torch.float32)
59
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
60
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
61
+ return self.weight * hidden_states.to(input_dtype)
62
+
63
+ def extra_repr(self):
64
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
65
+
66
+
67
+ class AionInstructMLP(nn.Module):
68
+ def __init__(self, config: AionInstructConfig):
69
+ super().__init__()
70
+ self.config = config
71
+ self.hidden_size = config.hidden_size
72
+ self.intermediate_size = config.intermediate_size
73
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
74
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
75
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
76
+ self.act_fn = ACT2FN[config.hidden_act]
77
+
78
+ def forward(self, x):
79
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
80
+ return down_proj
81
+
82
+
83
+ class AionInstructRotaryEmbedding(nn.Module):
84
+ """Rotary position embeddings with separate parameters for each attention layer type."""
85
+
86
+ def __init__(self, config: AionInstructConfig):
87
+ super().__init__()
88
+ self.max_seq_len_cached = config.max_position_embeddings
89
+ self.original_max_seq_len = config.max_position_embeddings
90
+ self.config = config
91
+ self.layer_types = sorted(set(config.layer_types))
92
+ self.rope_type = {}
93
+ for layer_type in self.layer_types:
94
+ self.rope_type[layer_type] = config.rope_parameters[layer_type]["rope_type"]
95
+ rope_init_fn: Callable = self.compute_default_rope_parameters
96
+ if self.rope_type[layer_type] != "default":
97
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type[layer_type]]
98
+ inv_freq, attention_scaling = rope_init_fn(config, layer_type=layer_type)
99
+ self.register_buffer(f"{layer_type}_inv_freq", inv_freq, persistent=False)
100
+ self.register_buffer(f"{layer_type}_original_inv_freq", inv_freq.clone(), persistent=False)
101
+ setattr(self, f"{layer_type}_attention_scaling", attention_scaling)
102
+
103
+ @staticmethod
104
+ def compute_default_rope_parameters(
105
+ config: AionInstructConfig,
106
+ device: torch.device | None = None,
107
+ seq_len: int | None = None,
108
+ layer_type: str | None = None,
109
+ **kwargs,
110
+ ) -> tuple[torch.Tensor, float]:
111
+ """
112
+ Computes the inverse frequencies according to the original RoPE implementation.
113
+
114
+ Args:
115
+ config ([`AionInstructConfig`]):
116
+ The model configuration.
117
+ device (`torch.device`, *optional*):
118
+ The device to use for initialization of the inverse frequencies.
119
+ seq_len (`int`, *optional*):
120
+ The current sequence length. Unused for this type of RoPE.
121
+ layer_type (`str`):
122
+ The attention type whose RoPE parameters are used.
123
+
124
+ Returns:
125
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
126
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
127
+ """
128
+ base = config.rope_parameters[layer_type]["rope_theta"]
129
+ dim = config.head_dim
130
+ attention_factor = 1.0 # Unused in this type of RoPE
131
+ inv_freq = 1.0 / (
132
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
133
+ )
134
+ return inv_freq, attention_factor
135
+
136
+ @torch.no_grad()
137
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
138
+ def forward(self, x, position_ids, layer_type):
139
+ inv_freq = getattr(self, f"{layer_type}_inv_freq")
140
+ attention_scaling = getattr(self, f"{layer_type}_attention_scaling")
141
+
142
+ inv_freq_expanded = inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
143
+ position_ids_expanded = position_ids[:, None, :].float()
144
+
145
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
146
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
147
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
148
+ emb = torch.cat((freqs, freqs), dim=-1)
149
+ cos = emb.cos() * attention_scaling
150
+ sin = emb.sin() * attention_scaling
151
+
152
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
153
+
154
+
155
+ def rotate_half(x):
156
+ """Rotates half the hidden dims of the input."""
157
+ x1 = x[..., : x.shape[-1] // 2]
158
+ x2 = x[..., x.shape[-1] // 2 :]
159
+ return torch.cat((-x2, x1), dim=-1)
160
+
161
+
162
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
163
+ """Applies Rotary Position Embedding to the query and key tensors.
164
+
165
+ Args:
166
+ q (`torch.Tensor`): The query tensor.
167
+ k (`torch.Tensor`): The key tensor.
168
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
169
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
170
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
171
+ The dimension along which to unsqueeze `cos` and `sin` (of shape `[batch_size, seq_len, head_dim]`) so
172
+ that they broadcast against `q` and `k` (of shape `[batch_size, heads, seq_len, head_dim]`).
173
+ Returns:
174
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
175
+ """
176
+ cos = cos.unsqueeze(unsqueeze_dim)
177
+ sin = sin.unsqueeze(unsqueeze_dim)
178
+ q_embed = (q * cos) + (rotate_half(q) * sin)
179
+ k_embed = (k * cos) + (rotate_half(k) * sin)
180
+ return q_embed, k_embed
181
+
182
+
183
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
184
+ """
185
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
186
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
187
+ """
188
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
189
+ if n_rep == 1:
190
+ return hidden_states
191
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
192
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
193
+
194
+
195
+ def eager_attention_forward(
196
+ module: nn.Module,
197
+ query: torch.Tensor,
198
+ key: torch.Tensor,
199
+ value: torch.Tensor,
200
+ attention_mask: torch.Tensor | None,
201
+ scaling: float,
202
+ dropout: float = 0.0,
203
+ **kwargs: Unpack[TransformersKwargs],
204
+ ):
205
+ key_states = repeat_kv(key, module.num_key_value_groups)
206
+ value_states = repeat_kv(value, module.num_key_value_groups)
207
+
208
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
209
+ if attention_mask is not None:
210
+ attn_weights = attn_weights + attention_mask
211
+
212
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
213
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
214
+ attn_output = torch.matmul(attn_weights, value_states)
215
+ attn_output = attn_output.transpose(1, 2).contiguous()
216
+
217
+ return attn_output, attn_weights
218
+
219
+
220
+ class AionInstructAttention(nn.Module):
221
+ """Grouped-query attention with RMSNorm on each query and key head, over the full context or a sliding window."""
222
+
223
+ def __init__(self, config: AionInstructConfig, layer_idx: int):
224
+ super().__init__()
225
+ self.config = config
226
+ self.layer_idx = layer_idx
227
+ self.layer_type = config.layer_types[layer_idx]
228
+ self.head_dim = config.head_dim
229
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
230
+ self.scaling = self.head_dim**-0.5
231
+ self.attention_dropout = config.attention_dropout
232
+ self.is_causal = True
233
+
234
+ self.q_proj = nn.Linear(
235
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
236
+ )
237
+ self.k_proj = nn.Linear(
238
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
239
+ )
240
+ self.v_proj = nn.Linear(
241
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
242
+ )
243
+ self.o_proj = nn.Linear(
244
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
245
+ )
246
+ self.q_norm = AionInstructRMSNorm(self.head_dim, eps=config.rms_norm_eps)
247
+ self.k_norm = AionInstructRMSNorm(self.head_dim, eps=config.rms_norm_eps)
248
+ self.sliding_window = config.sliding_window if self.layer_type == "sliding_attention" else None
249
+
250
+ def forward(
251
+ self,
252
+ hidden_states: torch.Tensor,
253
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
254
+ attention_mask: torch.Tensor | None,
255
+ past_key_values: Cache | None = None,
256
+ **kwargs: Unpack[FlashAttentionKwargs],
257
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
258
+ input_shape = hidden_states.shape[:-1]
259
+ hidden_shape = (*input_shape, -1, self.head_dim)
260
+
261
+ query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
262
+ key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
263
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
264
+
265
+ cos, sin = position_embeddings
266
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
267
+
268
+ if past_key_values is not None:
269
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
270
+
271
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
272
+ self.config._attn_implementation, eager_attention_forward
273
+ )
274
+
275
+ attn_output, attn_weights = attention_interface(
276
+ self,
277
+ query_states,
278
+ key_states,
279
+ value_states,
280
+ attention_mask,
281
+ dropout=0.0 if not self.training else self.attention_dropout,
282
+ scaling=self.scaling,
283
+ sliding_window=self.sliding_window,
284
+ **kwargs,
285
+ )
286
+
287
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
288
+ attn_output = self.o_proj(attn_output)
289
+ return attn_output, attn_weights
290
+
291
+
292
+ class AionInstructDecoderLayer(GradientCheckpointingLayer):
293
+ def __init__(self, config: AionInstructConfig, layer_idx: int):
294
+ super().__init__()
295
+ self.hidden_size = config.hidden_size
296
+ self.self_attn = AionInstructAttention(config=config, layer_idx=layer_idx)
297
+ self.mlp = AionInstructMLP(config)
298
+ self.input_layernorm = AionInstructRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
299
+ self.post_attention_layernorm = AionInstructRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
300
+
301
+ def forward(
302
+ self,
303
+ hidden_states: torch.Tensor,
304
+ attention_mask: torch.Tensor | None = None,
305
+ position_ids: torch.LongTensor | None = None,
306
+ past_key_values: Cache | None = None,
307
+ use_cache: bool | None = False,
308
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
309
+ **kwargs: Unpack[TransformersKwargs],
310
+ ) -> torch.Tensor:
311
+ residual = hidden_states
312
+ hidden_states = self.input_layernorm(hidden_states)
313
+ # Self Attention
314
+ hidden_states, _ = self.self_attn(
315
+ hidden_states=hidden_states,
316
+ attention_mask=attention_mask,
317
+ position_ids=position_ids,
318
+ past_key_values=past_key_values,
319
+ use_cache=use_cache,
320
+ position_embeddings=position_embeddings,
321
+ **kwargs,
322
+ )
323
+ hidden_states = residual + hidden_states
324
+
325
+ # Fully Connected
326
+ residual = hidden_states
327
+ hidden_states = self.post_attention_layernorm(hidden_states)
328
+ hidden_states = self.mlp(hidden_states)
329
+ hidden_states = residual + hidden_states
330
+ return hidden_states
331
+
332
+
333
+ class AionInstructPreTrainedModel(PreTrainedModel):
334
+ config: AionInstructConfig
335
+ base_model_prefix = "model"
336
+ supports_gradient_checkpointing = True
337
+ _no_split_modules = ["AionInstructDecoderLayer"]
338
+ _skip_keys_device_placement = ["past_key_values"]
339
+ _supports_flash_attn = True
340
+ _supports_sdpa = True
341
+ _supports_flex_attn = True
342
+
343
+ _can_compile_fullgraph = True
344
+ _supports_attention_backend = True
345
+ _can_record_outputs = {
346
+ "hidden_states": AionInstructDecoderLayer,
347
+ "attentions": AionInstructAttention,
348
+ }
349
+
350
+ @torch.no_grad()
351
+ def _init_weights(self, module):
352
+ super()._init_weights(module)
353
+ if isinstance(module, AionInstructRotaryEmbedding):
354
+ for layer_type in module.layer_types:
355
+ rope_init_fn = module.compute_default_rope_parameters
356
+ if module.rope_type[layer_type] != "default":
357
+ rope_init_fn = ROPE_INIT_FUNCTIONS[module.rope_type[layer_type]]
358
+ inv_freq, _ = rope_init_fn(module.config, layer_type=layer_type)
359
+ init.copy_(getattr(module, f"{layer_type}_inv_freq"), inv_freq)
360
+ init.copy_(getattr(module, f"{layer_type}_original_inv_freq"), inv_freq)
361
+
362
+
363
+ class AionInstructModel(AionInstructPreTrainedModel):
364
+ def __init__(self, config: AionInstructConfig):
365
+ super().__init__(config)
366
+ self.padding_idx = config.pad_token_id
367
+ self.vocab_size = config.vocab_size
368
+
369
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
370
+ self.layers = nn.ModuleList(
371
+ [AionInstructDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
372
+ )
373
+ self.norm = AionInstructRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
374
+ self.rotary_emb = AionInstructRotaryEmbedding(config=config)
375
+ self.gradient_checkpointing = False
376
+ self.has_sliding_layers = "sliding_attention" in self.config.layer_types
377
+
378
+ # Initialize weights and apply final processing
379
+ self.post_init()
380
+
381
+ @merge_with_config_defaults
382
+ @capture_outputs
383
+ def forward(
384
+ self,
385
+ input_ids: torch.LongTensor | None = None,
386
+ attention_mask: torch.Tensor | None = None,
387
+ position_ids: torch.LongTensor | None = None,
388
+ past_key_values: Cache | None = None,
389
+ inputs_embeds: torch.FloatTensor | None = None,
390
+ use_cache: bool | None = None,
391
+ **kwargs: Unpack[TransformersKwargs],
392
+ ) -> BaseModelOutputWithPast:
393
+ if (input_ids is None) ^ (inputs_embeds is not None):
394
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
395
+
396
+ if inputs_embeds is None:
397
+ inputs_embeds = self.embed_tokens(input_ids)
398
+
399
+ if use_cache and past_key_values is None:
400
+ past_key_values = DynamicCache(config=self.config)
401
+
402
+ if position_ids is None:
403
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
404
+ position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
405
+ position_ids = position_ids.unsqueeze(0)
406
+
407
+ # It may already have been prepared by e.g. `generate`
408
+ if not isinstance(causal_mask_mapping := attention_mask, dict):
409
+ # Prepare mask arguments
410
+ mask_kwargs = {
411
+ "config": self.config,
412
+ "inputs_embeds": inputs_embeds,
413
+ "attention_mask": attention_mask,
414
+ "past_key_values": past_key_values,
415
+ "position_ids": position_ids,
416
+ }
417
+ # Create the masks
418
+ causal_mask_mapping = {
419
+ "full_attention": create_causal_mask(**mask_kwargs),
420
+ }
421
+ if self.has_sliding_layers:
422
+ causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
423
+
424
+ hidden_states = inputs_embeds
425
+ position_embeddings = {
426
+ layer_type: self.rotary_emb(hidden_states, position_ids, layer_type)
427
+ for layer_type in self.rotary_emb.layer_types
428
+ }
429
+
430
+ for i, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
431
+ layer_type = self.config.layer_types[i]
432
+ hidden_states = decoder_layer(
433
+ hidden_states,
434
+ attention_mask=causal_mask_mapping[layer_type],
435
+ position_embeddings=position_embeddings[layer_type],
436
+ position_ids=position_ids,
437
+ past_key_values=past_key_values,
438
+ use_cache=use_cache,
439
+ **kwargs,
440
+ )
441
+
442
+ hidden_states = self.norm(hidden_states)
443
+ return BaseModelOutputWithPast(
444
+ last_hidden_state=hidden_states,
445
+ past_key_values=past_key_values if use_cache else None,
446
+ )
447
+
448
+
449
+ class AionInstructForCausalLM(AionInstructPreTrainedModel, GenerationMixin):
450
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
451
+ _tp_plan = {"lm_head": "colwise_gather_output"}
452
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
453
+ _fsdp_plan = {"lm_head": "keep_full_weight"}
454
+
455
+ def __init__(self, config: AionInstructConfig):
456
+ super().__init__(config)
457
+ self.model = AionInstructModel(config)
458
+ self.vocab_size = config.vocab_size
459
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
460
+
461
+ # Initialize weights and apply final processing
462
+ self.post_init()
463
+
464
+ @can_return_tuple
465
+ def forward(
466
+ self,
467
+ input_ids: torch.LongTensor | None = None,
468
+ attention_mask: torch.Tensor | None = None,
469
+ position_ids: torch.LongTensor | None = None,
470
+ past_key_values: Cache | None = None,
471
+ inputs_embeds: torch.FloatTensor | None = None,
472
+ labels: torch.LongTensor | None = None,
473
+ use_cache: bool | None = None,
474
+ logits_to_keep: int | torch.Tensor = 0,
475
+ **kwargs: Unpack[TransformersKwargs],
476
+ ) -> CausalLMOutputWithPast:
477
+ r"""
478
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
479
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
480
+ config.vocab_size - 1]` or -100. Tokens with indices set to `-100` are ignored (masked), the loss is only
481
+ computed for the tokens with labels in `[0, ..., config.vocab_size - 1]`.
482
+ logits_to_keep (`int` or `torch.Tensor`, *optional*, defaults to 0):
483
+ If an `int`, compute logits for the last `logits_to_keep` tokens (all tokens if 0). If a `torch.Tensor`,
484
+ the sequence indices to keep.
485
+
486
+ Example:
487
+
488
+ ```python
489
+ >>> from transformers import AutoTokenizer, AionInstructForCausalLM
490
+
491
+ >>> model = AionInstructForCausalLM.from_pretrained(checkpoint)
492
+ >>> tokenizer = AutoTokenizer.from_pretrained(checkpoint)
493
+
494
+ >>> messages = [{"role": "user", "content": "Write a haiku about the sea."}]
495
+ >>> inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt")
496
+ >>> outputs = model.generate(**inputs, max_new_tokens=64)
497
+ >>> print(tokenizer.decode(outputs[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True))
498
+ ```"""
499
+ outputs: BaseModelOutputWithPast = self.model(
500
+ input_ids=input_ids,
501
+ attention_mask=attention_mask,
502
+ position_ids=position_ids,
503
+ past_key_values=past_key_values,
504
+ inputs_embeds=inputs_embeds,
505
+ use_cache=use_cache,
506
+ **kwargs,
507
+ )
508
+
509
+ hidden_states = outputs.last_hidden_state
510
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
511
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
512
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
513
+
514
+ loss = None
515
+ if labels is not None:
516
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
517
+
518
+ return CausalLMOutputWithPast(
519
+ loss=loss,
520
+ logits=logits,
521
+ past_key_values=outputs.past_key_values,
522
+ hidden_states=outputs.hidden_states,
523
+ attentions=outputs.attentions,
524
+ )
525
+
526
+
527
+ __all__ = ["AionInstructForCausalLM", "AionInstructModel", "AionInstructPreTrainedModel"]
recipe.yaml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ default_stage:
2
+ default_modifiers:
3
+ GPTQModifier:
4
+ targets: [Linear]
5
+ ignore: [lm_head]
6
+ scheme: NVFP4
7
+ bypass_divisibility_checks: false
8
+ requires_calibration_data: true
9
+ block_size: 128
10
+ dampening_frac: 0.01
11
+ actorder: static
12
+ batched_quantization: auto
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7ea8bdf68c3e7549a3fb4342523288ce628f6ab56a618f9a4dfb234a0b4d46a8
3
+ size 15524476
tokenizer_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "backend": "tokenizers",
4
+ "bos_token": "<|endoftext|>",
5
+ "clean_up_tokenization_spaces": false,
6
+ "eos_token": "<|end|>",
7
+ "is_local": true,
8
+ "local_files_only": false,
9
+ "model_max_length": 32768,
10
+ "pad_token": "<|endoftext|>",
11
+ "tokenizer_class": "TokenizersBackend",
12
+ "unk_token": "<|endoftext|>"
13
+ }