-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathbuilder.py
1994 lines (1739 loc) · 112 KB
/
builder.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""
Run this script to create the desired ONNX model.
"""
from onnx import helper, numpy_helper, TensorProto, external_data_helper, save_model
from onnxruntime.quantization.matmul_4bits_quantizer import MatMul4BitsQuantizer
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, GenerationConfig
import numpy as np
import torch
import argparse
import gc
import json
import os
import textwrap
class Model:
def __init__(self, config, io_dtype, onnx_dtype, ep, cache_dir, extra_options):
self.context_length = config.max_position_embeddings
self.window_size = config.sliding_window if hasattr(config, "sliding_window") else -1 # default is -1 in GroupQueryAttention kernel
self.intermediate_size = config.intermediate_size
self.hidden_size = config.hidden_size
self.num_kv_heads = config.num_key_value_heads if hasattr(config, "num_key_value_heads") else config.num_attention_heads
self.num_attn_heads = config.num_attention_heads
self.head_size = config.head_dim if hasattr(config, "head_dim") else config.hidden_size // config.num_attention_heads
self.num_layers = int(extra_options["num_hidden_layers"]) if "num_hidden_layers" in extra_options else config.num_hidden_layers
self.vocab_size = config.vocab_size
self.activation = config.hidden_act
self.model_name_or_path = config._name_or_path
self.model_type = config.architectures[0]
self.io_dtype = io_dtype # {'fp16', 'fp32'}
self.onnx_dtype = onnx_dtype # {"int4", "fp16", "fp32"}
self.cache_dir = cache_dir
self.filename = extra_options["filename"] if "filename" in extra_options else "model.onnx"
self.extra_options = extra_options
self.inputs = []
self.outputs = []
self.initializers = []
self.value_infos = []
self.nodes = []
# EP-specific variables
enable_cuda_graph = "1" if "enable_cuda_graph" in extra_options and extra_options["enable_cuda_graph"] == "1" else "0"
self.ep = ep
self.ep_attrs = {
"cpu": {},
"cuda": {
"enable_cuda_graph": enable_cuda_graph, # "1" if the the model is able to enable cuda graph, "0" otherwise
},
"dml": {},
}
# Map input names to their types and shapes
self.input_names = ["input_ids", "attention_mask", "position_ids"]
self.input_types = {
"input_ids": TensorProto.INT64, # For standard models
"attention_mask": TensorProto.INT64, # For standard models
"position_ids": TensorProto.INT64, # For standard models
"inputs_embeds": self.io_dtype, # For standard models where you want to remove the embedding layer from the model (note that `inputs_embeds` is written this way to match Hugging Face format)
"past_key_values.key": self.io_dtype, # For standard models (note that `past_key_values.key` is written this way to match Hugging Face format)
"past_key_values.value": self.io_dtype, # For standard models (note that `past_key_values.value` is written this way to match Hugging Face format)
}
self.input_shapes = {
"input_ids": ["batch_size", "sequence_length"], # For standard models
"attention_mask": ["batch_size", "total_sequence_length"], # For standard models
"position_ids": ["batch_size", "sequence_length"], # For standard models
"inputs_embeds": ["batch_size", "sequence_length", self.hidden_size], # For standard models where you want to remove the embedding layer from the model (note that `inputs_embeds` is written this way to match Hugging Face format)
"past_key_values.key": ["batch_size", self.num_kv_heads, "past_sequence_length", self.head_size], # For standard models (note that `past_key_values.key` is written this way to match Hugging Face format)
"past_key_values.value": ["batch_size", self.num_kv_heads, "past_sequence_length", self.head_size], # For standard models (note that `past_key_values.value` is written this way to match Hugging Face format)
}
self.exclude_embeds = "exclude_embeds" in extra_options
if self.exclude_embeds:
self.input_names = [name.replace("input_ids", "inputs_embeds") for name in self.input_names]
# Map output names to their types and shapes
self.output_names = ["logits"]
self.output_types = {
"hidden_states": self.io_dtype, # For standard models where you want to remove the language modeling head from the model (note that `hidden_states` is written this way to match Hugging Face format)
"logits": self.io_dtype, # For standard models
"present.key": self.io_dtype, # For standard models (note that `present.key` is written this way to match Hugging Face format)
"present.value": self.io_dtype, # For standard models (note that `present.value` is written this way to match Hugging Face format)
}
self.output_shapes = {
"hidden_states": ["batch_size", "sequence_length", self.hidden_size], # For standard models where you want to remove the language modeling head from the model (note that `hidden_states` is written this way to match Hugging Face format)
"logits": ["batch_size", "sequence_length", self.vocab_size], # For standard models
"present.key": ["batch_size", self.num_kv_heads, "total_sequence_length", self.head_size], # For standard models (note that `present.key` is written this way to match Hugging Face format)
"present.value": ["batch_size", self.num_kv_heads, "total_sequence_length", self.head_size], # For standard models (note that `present.value` is written this way to match Hugging Face format)
}
self.exclude_lm_head = "exclude_lm_head" in extra_options
if self.exclude_lm_head:
self.output_names = [name.replace("logits", "hidden_states") for name in self.output_names]
# Store names of nodes already created
self.node_names = set()
# Map TensorProto dtypes to NumPy dtypes
self.to_numpy_dtype = {
TensorProto.INT8: np.uint8,
TensorProto.INT32: np.int32,
TensorProto.INT64: np.int64,
TensorProto.FLOAT16: np.float16,
TensorProto.FLOAT: np.float32,
}
# Map TensorProto dtypes to string dtypes
self.to_str_dtype = {
TensorProto.INT8: "TensorProto.INT8",
TensorProto.INT32: "TensorProto.INT32",
TensorProto.INT64: "TensorProto.INT64",
TensorProto.FLOAT16: "TensorProto.FLOAT16",
TensorProto.FLOAT: "TensorProto.FLOAT",
}
# Mask-specific variables
self.mask_attrs = {
"mask_name": "", # Name of node that outputs 4D causal attention mask (used as add_qk in MultiHeadAttention)
"seqlens_k": "", # Sum of each row in attention mask - 1 (used as input to GroupQueryAttention)
"total_seq_len": "", # Size of total sequence length in attention mask (used as input to GroupQueryAttention)
}
# Embedding-specific variables
self.embed_attrs = {
"scale": 1, # Scale value to multiply output of Embedding layer by
}
# LayerNorm-specific variables
self.layernorm_attrs = {
"simple": True, # Use SimplifiedLayerNorm/SkipSimplifiedLayerNorm vs. LayerNorm/SkipLayerNorm
"first_layernorm": True, # 1st LayerNorm = LayerNorm, then SkipLayerNorm for all subsequent LayerNorms
"last_layernorm": False, # Last LayerNorm = SkipLayerNorm with only output 0 (no output 3)
"root_input": "", # Root input from parent node for LayerNorm and SkipLayerNorm
"skip_input": "", # Skip input from parent node for SkipLayerNorm
"output_0": "", # Output 0 for LayerNorm and SkipLayerNorm
"output_3": "", # Output 3 for SkipLayerNorm
"add_offset": 0, # Offset value for LayerNorm weight
}
# RotaryEmbedding-specific variables
short_factor = config.rope_scaling["short_factor"] if hasattr(config, "rope_scaling") and config.rope_scaling is not None else []
long_factor = config.rope_scaling["long_factor"] if hasattr(config, "rope_scaling") and config.rope_scaling is not None else []
partial_rotary_factor = config.partial_rotary_factor if hasattr(config, "partial_rotary_factor") else 1.0
rope_theta = config.rope_theta if hasattr(config, "rope_theta") else 10000
self.rotemb_attrs = {
"create_rotary_embedding_caches": True, # Create cos/sin caches for rotary embeddings
"theta": rope_theta, # Base value if calculating cos/sin caches from scratch
"short_factor": short_factor, # Short factor for PhiLongRoPE
"long_factor": long_factor, # Long factor for PhiLongRoPE
"partial_rotary_factor": partial_rotary_factor, # Factor for partial rotary embeddings
"interleaved": 0, # Interleave the rotary embeddings (e.g. [0, 0, 0, 1, 1, 1] to [0, 1, 0, 1, 0, 1], RotaryEmbedding kernel expects a default value of 0)
"num_heads": 0, # For partial rotary embeddings (RotaryEmbedding kernel expects a default value of 0)
"rotary_embedding_dim": 0, # For partial rotary embeddings (RotaryEmbedding kernel expects a default value of 0)
}
# Attention-specific variables (MHA, GQA, GQA + Rot.Emb., etc.)
self.attention_attrs = {
"op_type": "MultiHeadAttention", # Attention op to use
"scale": 1 / np.sqrt(self.head_size), # Scale value after calculating Q x K' in attention
"use_rotemb_in_attn": False, # Use rotary embeddings within attention op (instead of a separate RotaryEmbedding op)
"use_packed_matmul": False, # Use packed MatMul (instead of 3 separate MatMuls for Q/K/V)
}
enable_GQA_on_CPU = True if "enable_GQA_on_CPU" in extra_options and extra_options["enable_GQA_on_CPU"] == "1" else False
if (self.ep in {"cuda", "dml"} and self.io_dtype == TensorProto.FLOAT16) or (enable_GQA_on_CPU and self.ep == "cpu" and self.io_dtype == TensorProto.FLOAT):
# Change model settings for GroupQueryAttention
self.attention_attrs["op_type"] = "GroupQueryAttention"
print("GroupQueryAttention (GQA) is used in this model. GQA is currently supported only for INT4 and FP16 on the CUDA and DML execution providers.")
# DML doesn't support packed Q/K/V for GQA yet
self.attention_attrs["use_packed_matmul"] = self.ep != "dml" and self.num_attn_heads == self.num_kv_heads
# GQA + Rot.Emb. does not require `position ids` as input
if self.ep in {"cuda", "cpu"}:
self.attention_attrs["use_rotemb_in_attn"] = True
self.input_names.remove("position_ids")
self.past_present_share_buffer = self.attention_attrs["op_type"] == "GroupQueryAttention"
# MLP-specific variables
self.mlp_attrs = {
"use_proj": True, # Use projection style for MLP (GateProj/UpProj/DownProj)
"use_fc": False, # Use fully-connected style for MLP (FC1/FC2)
"output_0": "", # Output 0 for MLP layer
}
# Quantization-specific variables (INT4, INT8, etc.)
self.quant_attrs = {
"int4": {
"block_size": int(extra_options["int4_block_size"]) if "int4_block_size" in extra_options else 32,
"accuracy_level": int(extra_options["int4_accuracy_level"]) if "int4_accuracy_level" in extra_options else None,
}
}
def make_genai_config(self, model_name_or_path, extra_kwargs, out_dir):
config = GenerationConfig.from_pretrained(model_name_or_path, **extra_kwargs)
inputs = dict(zip(self.input_names, self.input_names))
inputs.update({
"past_key_names": "past_key_values.%d.key",
"past_value_names": "past_key_values.%d.value",
})
genai_config = {
"model": {
"bos_token_id": config.bos_token_id,
"context_length": self.context_length,
"decoder": {
"session_options" : {
"log_id": "onnxruntime-genai",
"provider_options" : []
},
"filename": self.filename,
"head_size": self.head_size,
"hidden_size": self.hidden_size,
"inputs": inputs,
"outputs": {
"logits": "logits",
"present_key_names": "present.%d.key",
"present_value_names": "present.%d.value",
},
"num_attention_heads": self.num_attn_heads,
"num_hidden_layers": self.num_layers,
"num_key_value_heads": self.num_kv_heads,
},
"eos_token_id": config.eos_token_id,
"pad_token_id": config.pad_token_id if hasattr(config, "pad_token_id") and config.pad_token_id is not None else config.eos_token_id[0] if isinstance(config.eos_token_id, list) else config.eos_token_id,
"type": self.model_type[ : self.model_type.find("For")].lower(),
"vocab_size": self.vocab_size,
},
"search": {
"diversity_penalty": config.diversity_penalty if hasattr(config, "diversity_penalty") else 0.0,
"do_sample": config.do_sample if hasattr(config, "do_sample") else False,
"early_stopping": True,
"length_penalty": config.length_penalty if hasattr(config, "length_penalty") else 1.0,
"max_length": self.context_length,
"min_length": 0,
"no_repeat_ngram_size": config.no_repeat_ngram_size if hasattr(config, "no_repeat_ngram_size") else 0,
"num_beams": config.num_beams if hasattr(config, "num_beams") else 1,
"num_return_sequences": config.num_return_sequences if hasattr(config, "num_return_sequences") else 1,
"past_present_share_buffer": self.past_present_share_buffer,
"repetition_penalty": config.repetition_penalty if hasattr(config, "repetition_penalty") else 1.0,
"temperature": config.temperature if hasattr(config, "temperature") else 1.0,
"top_k": 1,
"top_p": config.top_p if hasattr(config, "top_p") else 1.0,
},
}
if self.ep != "cpu":
ep_options = { self.ep : self.ep_attrs[self.ep] }
genai_config["model"]["decoder"]["session_options"]["provider_options"].append(ep_options)
print(f"Saving GenAI config in {out_dir}")
with open(os.path.join(out_dir,"genai_config.json"), "w") as f:
json.dump(genai_config, f, indent=4)
def save_processing(self, model_name_or_path, extra_kwargs, out_dir):
tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, **extra_kwargs)
print(f"Saving processing files in {out_dir} for GenAI")
tokenizer.save_pretrained(out_dir)
def save_model(self, out_dir):
print(f"Saving ONNX model in {out_dir}")
gc.collect()
# Create ONNX model
model = helper.make_model(
opset_imports=[self.clear_field(helper.make_operatorsetid('', 14), 'domain'), helper.make_operatorsetid('com.microsoft', 1)],
ir_version=7,
producer_name="onnxruntime-genai",
producer_version="0.0.0",
graph=self.make_graph(
name="main_graph",
inputs=self.inputs,
outputs=self.outputs,
initializer=self.initializers,
value_info=self.value_infos,
nodes=self.nodes,
)
)
# Load external data into ONNX model
external_data_helper.load_external_data_for_model(model, self.cache_dir)
# Delete external data files on disk before re-saving
for path in os.listdir(self.cache_dir):
if path.endswith(".bin"):
os.remove(os.path.join(self.cache_dir, path))
# Delete temporary cache dir if empty
if len(os.listdir(self.cache_dir)) == 0:
os.rmdir(self.cache_dir)
# Quantize ONNX model to desired precision
# TODO: Replace by quantizing the MatMuls as they are created
if self.onnx_dtype == "int4":
model = self.to_int4(model)
# Save ONNX model with only one external data file and delete any existing duplicate copies
out_path = os.path.join(out_dir, self.filename)
data_path = os.path.join(out_dir, os.path.basename(out_path) + ".data")
if os.path.exists(out_path):
print(f"Overwriting {out_path}")
os.remove(out_path)
if os.path.exists(data_path):
print(f"Overwriting {data_path}")
os.remove(data_path)
save_model(
model,
out_path,
save_as_external_data=True,
all_tensors_to_one_file=True,
location=os.path.basename(data_path),
size_threshold=0,
convert_attribute=False,
)
def to_int4(self, model):
quant = MatMul4BitsQuantizer(
model=model,
block_size=self.quant_attrs["int4"]["block_size"],
is_symmetric=True,
accuracy_level=self.quant_attrs["int4"]["accuracy_level"],
nodes_to_exclude=[],
)
quant.process()
return quant.model.model
def clear_field(self, proto, field):
proto.ClearField(field)
return proto
def order_repeated_field(self, repeated_proto, key_name, order):
order = list(order)
repeated_proto.sort(key=lambda x: order.index(getattr(x, key_name)))
def make_external_tensor(self, np_data, name, **kwargs):
tensor = numpy_helper.from_array(np_data)
tensor.name = name
filename = f"{name}.bin"
external_data_helper.set_external_data(tensor, location=filename)
with open(os.path.join(self.cache_dir, filename), "wb") as f:
f.write(tensor.raw_data)
tensor.ClearField("raw_data")
tensor.data_location = TensorProto.EXTERNAL
self.initializers.append(tensor)
def make_node(self, op_type, inputs, outputs, name=None, doc_string=None, domain=None, **kwargs):
# Save any constants as nodes
for input_name in inputs:
if input_name.startswith("/model/constants") and input_name not in self.node_names:
self.make_constant(input_name)
# Make node only if it does not already exist
if name not in self.node_names:
node = helper.make_node(op_type, inputs, outputs, name, doc_string, domain, **kwargs)
if doc_string == '':
node.doc_string = ''
self.order_repeated_field(node.attribute, 'name', kwargs.keys())
self.nodes.append(node)
self.node_names.add(name)
# Note:
#
# The above approach allows functions that make similar subgraphs with the same naming schema
# to share existing nodes without needing to know whether the nodes already exist or not
# (e.g. attention mask subgraphs).
#
# This means that the nodes can be created in those functions regardless of their actual
# status in the graph. The above checks can then decide whether the proposed node actually
# needs to be added into the graph or not.
def make_value_info(self, name, dtype, shape):
value_info = helper.make_tensor_value_info(name, dtype, shape=shape)
self.value_infos.append(value_info)
def make_graph(self, *args, doc_string=None, **kwargs):
graph = helper.make_graph(*args, doc_string=doc_string, **kwargs)
if doc_string == '':
graph.doc_string = ''
return graph
def make_inputs_and_outputs(self):
# Add model-specific inputs to list of model inputs
inputs = []
for name in self.input_names:
dtype = self.input_types[name]
shape = self.input_shapes[name]
inputs.append(helper.make_tensor_value_info(name, dtype, shape=shape))
# Add model-specific outputs to list of model outputs
outputs = []
for name in self.output_names:
dtype = self.output_types[name]
shape = self.output_shapes[name]
outputs.append(helper.make_tensor_value_info(name, dtype, shape=shape))
# Add KV cache to inputs and outputs
for i in range(self.num_layers):
# Add KV cache to inputs
key_name = f"past_key_values.{i}.key"
inputs.append(helper.make_tensor_value_info(key_name, self.input_types["past_key_values.key"], shape=self.input_shapes["past_key_values.key"]))
value_name = f"past_key_values.{i}.value"
inputs.append(helper.make_tensor_value_info(value_name, self.input_types["past_key_values.value"], shape=self.input_shapes["past_key_values.value"]))
# Add KV cache to outputs
key_name = f"present.{i}.key"
outputs.append(helper.make_tensor_value_info(key_name, self.output_types["present.key"], shape=self.output_shapes["present.key"]))
value_name = f"present.{i}.value"
outputs.append(helper.make_tensor_value_info(value_name, self.output_types["present.value"], shape=self.output_shapes["present.value"]))
self.inputs = inputs
self.outputs = outputs
def make_constant(self, name):
# Make constant ops for 0, 1, 2, 3, etc.
# Format of name is "/model/constants/{dtype}/{shape}/{num}"
path = name.split("/")
onnx_dtype, dims, num = eval(path[-3]), path[-2], eval(path[-1])
np_dtype = self.to_numpy_dtype[onnx_dtype]
value = numpy_helper.from_array(np.array(num if dims == "0D" else list(num) if type(num) == tuple else [num], dtype=np_dtype), name=name.replace("constants", "numpy_helper"))
node_name = name.replace("constants", "constant_nodes")
self.make_node("Constant", inputs=[], outputs=[name], name=node_name, value=value)
self.make_value_info(name, onnx_dtype, shape=[])
self.node_names.add(name)
def make_gather(self, name, inputs, axis):
output = f"{name}/output_0"
self.make_node("Gather", inputs=inputs, outputs=[output], name=name, axis=axis)
self.make_value_info(output, TensorProto.INT64, shape=[])
def make_reshape(self, name, inputs, dtype, shape):
output = f"{name}/output_0"
self.make_node("Reshape", inputs=inputs, outputs=[output], name=name)
self.make_value_info(output, dtype, shape=shape)
def make_shape(self, name, root_input, shape):
output = f"{name}/output_0"
self.make_node("Shape", inputs=[root_input], outputs=[output], name=name)
self.make_value_info(output, TensorProto.INT64, shape=shape)
def make_constant_of_shape(self, name, root_input, value, dtype, shape):
output = f"{name}/output_0"
self.make_node("ConstantOfShape", inputs=[root_input], outputs=[output], name=name, value=value)
self.make_value_info(output, dtype, shape=shape)
def make_unsqueeze(self, name, inputs, dtype, shape):
output = f"{name}/output_0"
self.make_node("Unsqueeze", inputs=inputs, outputs=[output], name=name)
self.make_value_info(output, dtype, shape=shape)
def make_squeeze(self, name, inputs):
output = f"{name}/output_0"
self.make_node("Squeeze", inputs=inputs, outputs=[output], name=name)
self.make_value_info(output, TensorProto.INT64, shape=[])
def make_concat(self, name, inputs, dtype, shape, axis=0):
output = f"{name}/output_0"
self.make_node("Concat", inputs=inputs, outputs=[output], name=name, axis=axis)
self.make_value_info(output, dtype, shape=shape)
def make_equal(self, name, inputs, shape):
output = f"{name}/output_0"
self.make_node("Equal", inputs=inputs, outputs=[output], name=name)
self.make_value_info(output, TensorProto.BOOL, shape=shape)
def make_greater(self, name, inputs, shape):
output = f"{name}/output_0"
self.make_node("Greater", inputs=inputs, outputs=[output], name=name)
self.make_value_info(output, TensorProto.BOOL, shape=shape)
def make_where(self, name, inputs, dtype, shape):
output = f"{name}/output_0"
self.make_node("Where", inputs=inputs, outputs=[output], name=name)
self.make_value_info(output, dtype, shape=shape)
def make_expand(self, name, inputs, dtype, shape):
output = f"{name}/output_0"
self.make_node("Expand", inputs=inputs, outputs=[output], name=name)
self.make_value_info(output, dtype, shape=shape)
def make_reduce_sum(self, name, inputs, dtype, shape):
output = f"{name}/output_0"
self.make_node("ReduceSum", inputs=inputs, outputs=[output], name=name)
self.make_value_info(output, dtype, shape=shape)
def make_cast(self, name, root_input, dtype, shape):
output = f"{name}/output_0"
self.make_node("Cast", inputs=[root_input], outputs=[output], name=name, to=dtype)
self.make_value_info(output, dtype, shape=shape)
def make_add(self, name, inputs, dtype, shape):
output = f"{name}/output_0"
self.make_node("Add", inputs=inputs, outputs=[output], name=name)
self.make_value_info(output, dtype, shape=shape)
def make_sub(self, name, inputs, dtype, shape):
output = f"{name}/output_0"
self.make_node("Sub", inputs=inputs, outputs=[output], name=name)
self.make_value_info(output, dtype, shape=shape)
def make_less(self, name, inputs):
output = f"{name}/output_0"
self.make_node("Less", inputs=inputs, outputs=[output], name=name)
self.make_value_info(output, TensorProto.BOOL, shape=None)
def make_range(self, name, inputs):
output = f"{name}/output_0"
self.make_node("Range", inputs=inputs, outputs=[output], name=name)
self.make_value_info(output, TensorProto.INT64, shape=["unk"])
def make_slice(self, name, inputs, dtype, shape):
output = f"{name}/output_0"
self.make_node("Slice", inputs=inputs, outputs=[output], name=name)
self.make_value_info(output, dtype, shape=shape)
def make_mul(self, name, inputs, dtype, shape):
output = f"{name}/output_0"
self.make_node("Mul", inputs=inputs, outputs=[output], name=name)
self.make_value_info(output, dtype, shape=shape)
def make_transpose(self, name, root_input, dtype, shape, perm):
output = f"{name}/output_0"
self.make_node("Transpose", inputs=[root_input], outputs=[output], name=name, perm=perm)
self.make_value_info(output, dtype, shape=shape)
def make_matmul(self, matmul, name, root_input, **kwargs):
self.make_matmul_fp16_or_fp32(matmul, name, root_input, **kwargs)
# TODO: add other dtypes
# if self.onnx_dtype in {"fp16", "fp32"}:
# self.make_matmul_fp16_or_fp32(matmul, name, root_input, **kwargs)
# elif self.onnx_dtype == "int8":
# pass
# elif self.onnx_dtype == "int4":
# int4_name = f"{name}NBits"
# self.make_matmul_int4(matmul, int4_name, root_input, **kwargs)
def make_matmul_fp16_or_fp32(self, matmul, name, root_input, **kwargs):
weight = name[1:].replace("/", ".") + ".weight"
self.make_external_tensor(matmul.transpose().astype(self.to_numpy_dtype[self.io_dtype]), weight)
last_dim = matmul.shape[0]
output = "logits" if kwargs.get("logits", False) else f"{name}/output_0"
self.make_node("MatMul", inputs=[root_input, weight], outputs=[output], name=name)
self.make_value_info(output, self.io_dtype, shape=['batch_size', 'sequence_length', last_dim])
# TODO: quantize weights, then save new MatMul numpy weights for onnx model
# def make_matmul_int4(self, matmul, name, root_input, **kwargs):
# weight = name[1:].replace("/", ".") + ".weight"
# scales = name[1:].replace("/", ".") + ".scales"
# output = "logits" if kwargs.get("logits", False) else f"{name}/output_0"
# self.make_node("MatMulNBits", inputs=[root_input, weight, scales], outputs=[output], name=name)
# self.make_value_info(output, self.io_dtype, shape=['batch_size', 'sequence_length', self.hidden_size])
def make_packed_matmul(self, q_matmul, k_matmul, v_matmul, name, root_input, **kwargs):
# N = num_heads * head_size, H = hidden_size
# Combine 3 Matmuls of shape NxH into 1 packed MatMul of shape 3NxH
# Note: Packed MatMul is of shape 3NxH instead of Hx3N because `make_matmul` will apply a transpose before saving
N, H = q_matmul.shape
matmul = np.stack((q_matmul.transpose(), k_matmul.transpose(), v_matmul.transpose()), axis=1).reshape(H, 3*N).transpose()
self.make_matmul(matmul, name, root_input, **kwargs)
def make_add_bias(self, add, name, root_input, **kwargs):
bias = name[1:].replace("/", ".") + ".bias"
self.make_external_tensor(add.astype(self.to_numpy_dtype[self.io_dtype]), bias)
add_bias_inputs = [root_input, bias]
shape = ['batch_size', 'sequence_length', add.shape[0]]
if "logits" in kwargs:
output = "logits"
self.make_node("Add", inputs=add_bias_inputs, outputs=[output], name=name)
self.make_value_info(output, dtype=self.io_dtype, shape=shape)
else:
self.make_add(name, add_bias_inputs, dtype=self.io_dtype, shape=shape)
def make_packed_add(self, q_add, k_add, v_add, name, root_input, **kwargs):
# Combine 3 Adds of shape H into 1 packed Add of shape 3H
add = np.stack((q_add, k_add, v_add), axis=0).flatten()
self.make_add_bias(add, name, root_input, **kwargs)
def make_embedding(self, embedding):
weight = "model.embed_tokens.weight"
self.make_external_tensor(embedding.astype(self.to_numpy_dtype[self.io_dtype]), weight)
basename = "/model/embed_tokens"
gather_name = f"{basename}/Gather"
gather_output = f"{gather_name}/output_0"
self.make_node('Gather', inputs=[weight, 'input_ids'], outputs=[gather_output], name=gather_name)
self.make_value_info(gather_output, self.io_dtype, shape=['batch_size', 'sequence_length', self.hidden_size])
if self.embed_attrs["scale"] != 1:
# Scale the embeddings
mul_name = f"{basename}/Mul"
mul_inputs = [gather_output, f"/model/constants/{self.to_str_dtype[self.io_dtype]}/0D/{self.embed_attrs['scale']}"]
mul_output = f"{mul_name}/output_0"
self.make_node('Mul', inputs=mul_inputs, outputs=[mul_output], name=mul_name)
self.make_value_info(mul_output, self.io_dtype, shape=['batch_size', 'sequence_length', self.hidden_size])
layernorm_attrs_value = mul_output
else:
layernorm_attrs_value = gather_output
self.layernorm_attrs["root_input"] = layernorm_attrs_value
self.layernorm_attrs["skip_input"] = layernorm_attrs_value
def make_layernorm(self, layer_id, layernorm, skip, simple, location):
root_input = self.layernorm_attrs["root_input"]
skip_input = self.layernorm_attrs["skip_input"]
weight = f"model.layers.{layer_id}.{location}_layernorm.weight"
self.make_external_tensor(layernorm.weight.detach().numpy().astype(self.to_numpy_dtype[self.io_dtype]) + self.layernorm_attrs["add_offset"], weight)
bias = f"model.layers.{layer_id}.{location}_layernorm.bias"
if not simple:
self.make_external_tensor(layernorm.bias.detach().numpy().astype(self.to_numpy_dtype[self.io_dtype]), bias)
inputs = [root_input, skip_input, weight] if skip else [root_input, weight]
if not simple:
inputs.append(bias)
name = f"/model/layers.{layer_id}/{location}_layernorm/{'Skip' if skip else ''}LayerNorm"
op_type = f"{'Skip' if skip else ''}{'Simplified' if simple else ''}LayerNormalization"
kwargs = {"epsilon": 9.999999747378752e-06}
if not skip:
kwargs.update({"axis": -1, "stash_type": 1})
output_0 = f"/model/layers.{layer_id}/{location}_layernorm/output_0"
output_3 = f"/model/layers.{layer_id}/{location}_layernorm/output_3"
if self.layernorm_attrs["last_layernorm"] and self.exclude_lm_head:
output_0 = "hidden_states"
outputs = [output_0, "", "", output_3] if skip and not self.layernorm_attrs["last_layernorm"] else [output_0]
self.make_node(op_type, inputs=inputs, outputs=outputs, name=name, domain=("com.microsoft" if skip else None), **kwargs)
self.make_value_info(output_0, self.io_dtype, shape=['batch_size', 'sequence_length', self.hidden_size])
if skip and not self.layernorm_attrs["last_layernorm"]:
self.make_value_info(output_3, self.io_dtype, shape=['batch_size', 'sequence_length', self.hidden_size])
# Update LayerNorm attributes
self.layernorm_attrs["output_0"] = output_0
if skip and not self.layernorm_attrs["last_layernorm"]:
self.layernorm_attrs["output_3"] = output_3
# Assign output 3 of current SkipLayerNorm as root input to next SkipLayerNorm
self.layernorm_attrs["root_input"] = output_3
return output_0
def make_rotary_embedding_caches(self, rotemb):
cos_cache_name, sin_cache_name = "cos_cache", "sin_cache"
if self.rotemb_attrs["create_rotary_embedding_caches"]:
if not hasattr(rotemb, "cos_cached"):
# Create cos/sin caches if not already created
dim = int(self.rotemb_attrs["partial_rotary_factor"] * self.head_size)
inv_freq = 1.0 / (self.rotemb_attrs["theta"] ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim))
t = torch.arange(self.context_length, dtype=torch.int64).type_as(inv_freq)
freqs = torch.outer(t, inv_freq)
emb = torch.cat((freqs, freqs), dim=-1)
cos_cache, sin_cache = emb.cos(), emb.sin()
else:
cos_cache, sin_cache = rotemb.cos_cached, rotemb.sin_cached
# Reshape cos/sin cache from (M, H) to (M, H/2)
hidden_dim = cos_cache.shape[-1]
cos_cache = cos_cache.squeeze()[:, : (hidden_dim // 2)].detach().numpy()
self.make_external_tensor(cos_cache.astype(self.to_numpy_dtype[self.io_dtype]), cos_cache_name)
sin_cache = sin_cache.squeeze()[:, : (hidden_dim // 2)].detach().numpy()
self.make_external_tensor(sin_cache.astype(self.to_numpy_dtype[self.io_dtype]), sin_cache_name)
self.rotemb_attrs["create_rotary_embedding_caches"] = False
return cos_cache_name, sin_cache_name
def make_rotary_embedding(self, rotemb, name, root_input, **kwargs):
cos_cache_name, sin_cache_name = self.make_rotary_embedding_caches(rotemb)
inputs = [root_input, kwargs.pop("position_ids"), cos_cache_name, sin_cache_name]
output = f"{name}/output_0"
self.make_node("RotaryEmbedding", inputs=inputs, outputs=[output], name=name, domain="com.microsoft", interleaved=self.rotemb_attrs["interleaved"], **kwargs)
self.make_value_info(output, self.io_dtype, shape=['batch_size', 'sequence_length', self.head_size * (self.num_kv_heads if "k_rotary" in name else self.num_attn_heads)])
# TODO: This function and any corresponding changes to support it are temporary until ORT supports GQA for CPU
def make_repeat_kv(self, layer_id, root_input, past_kv, present_kv, **kwargs):
# Make subgraph that repeats tensor of shape (batch_size, sequence_length, num_kv_heads, head_size)
# to shape (batch_size, sequence_length, num_attn_heads, head_size) in an interleaved pattern
# and updates the KV caches
#
# root_input
# |
# Reshape
# |
# Transpose
# |
# | past_kv
# | /
# Concat
# | \
# | present_kv
# |
# +-------+---------+
# | |
# | Shape
# | |
# | +-----------+-----------+-----------+
# | | | | |
# | Gather Gather Gather Gather
# | (idx=0) (idx=1) (idx=2) (idx=3)
# | | | | |
# | Unsqueeze Unsqueeze Unsqueeze Unsqueeze
# | | | | |
# | +-----------+-----------+-----------+
# | |
# | +-----------------------+
# | | |
# | | Mul
# | | |
# | Concat Concat
# | (5D) (4D)
# | | |
# | Reshape |
# | / | \ |
# | / | \ |
# | / | \ /
# | / | \ /
# | / | \ /
# | / Shape \ /
# | / | \ /
# | | ConstantOfShape \ /
# | \ | \ \ /
# | \ | Mul | /
# | \ | | / /
# | \ | Equal /
# | \ | / /
# \ \ | / /
# \ \ | / /
# \ \ | / /
# \ \ | / /
# Unsqueeze Where /
# \ / /
# \ / /
# \ / /
# \ / /
# Expand /
# | /
# | /
# | /
# | /
# | /
# Reshape
# |
# Transpose
# |
# Reshape
basename = f"/model/layers.{layer_id}/attn/{'k_proj' if past_kv.endswith('key') else 'v_proj'}/repeat_kv"
# Make the initial subgraph
#
# +------> Gather --> Unsqueeze -----+
# | |
# past_kv +------> Gather --> Unsqueeze -----+---> Mul --> Concat (4D)
# | | |
# root_input --> Reshape --> Transpose --> Concat --> Shape ---> Gather --> Unsqueeze -----+---> Concat (5D)
# | | |
# present_kv +------> Gather --> Unsqueeze -----+
reshape_1_name = f"{basename}/Reshape_1"
reshape_1_inputs = [root_input, f"/model/constants/TensorProto.INT64/1D/0, 0, {self.num_kv_heads}, -1"]
self.make_reshape(reshape_1_name, reshape_1_inputs, dtype=self.io_dtype, shape=['batch_size', 'sequence_length', self.num_kv_heads, self.head_size])
transpose_1_name = f"{basename}/Transpose_1"
transpose_1_input = f"{reshape_1_name}/output_0"
self.make_transpose(transpose_1_name, transpose_1_input, dtype=self.io_dtype, shape=['batch_size', self.num_kv_heads, 'sequence_length', self.head_size], perm=[0,2,1,3])
concat_1_name = f"{basename}/Concat_1"
concat_1_inputs = [past_kv, f"{transpose_1_name}/output_0"]
self.make_node("Concat", inputs=concat_1_inputs, outputs=[present_kv], name=concat_1_name, axis=2)
shape_1_name = f"{basename}/Shape_1"
self.make_shape(shape_1_name, present_kv, shape=[4])
gather_1_name = f"{basename}/Gather_1"
gather_1_inputs = [f"{shape_1_name}/output_0", "/model/constants/TensorProto.INT64/0D/0"]
self.make_gather(gather_1_name, gather_1_inputs, axis=0)
unsqueeze_1_name = f"{basename}/Unsqueeze_1"
unsqueeze_1_inputs = [f"{gather_1_name}/output_0", "/model/constants/TensorProto.INT64/1D/0"]
self.make_unsqueeze(unsqueeze_1_name, unsqueeze_1_inputs, dtype=TensorProto.INT64, shape=[1])
gather_2_name = f"{basename}/Gather_2"
gather_2_inputs = [f"{shape_1_name}/output_0", "/model/constants/TensorProto.INT64/0D/1"]
self.make_gather(gather_2_name, gather_2_inputs, axis=0)
unsqueeze_2_name = f"{basename}/Unsqueeze_2"
unsqueeze_2_inputs = [f"{gather_2_name}/output_0", "/model/constants/TensorProto.INT64/1D/0"]
self.make_unsqueeze(unsqueeze_2_name, unsqueeze_2_inputs, dtype=TensorProto.INT64, shape=[1])
gather_3_name = f"{basename}/Gather_3"
gather_3_inputs = [f"{shape_1_name}/output_0", "/model/constants/TensorProto.INT64/0D/2"]
self.make_gather(gather_3_name, gather_3_inputs, axis=0)
unsqueeze_3_name = f"{basename}/Unsqueeze_3"
unsqueeze_3_inputs = [f"{gather_3_name}/output_0", "/model/constants/TensorProto.INT64/1D/0"]
self.make_unsqueeze(unsqueeze_3_name, unsqueeze_3_inputs, dtype=TensorProto.INT64, shape=[1])
gather_4_name = f"{basename}/Gather_4"
gather_4_inputs = [f"{shape_1_name}/output_0", "/model/constants/TensorProto.INT64/0D/3"]
self.make_gather(gather_4_name, gather_4_inputs, axis=0)
unsqueeze_4_name = f"{basename}/Unsqueeze_4"
unsqueeze_4_inputs = [f"{gather_4_name}/output_0", "/model/constants/TensorProto.INT64/1D/0"]
self.make_unsqueeze(unsqueeze_4_name, unsqueeze_4_inputs, dtype=TensorProto.INT64, shape=[1])
concat_2_name = f"{basename}/Concat_2"
concat_2_inputs = [f"{unsqueeze_1_name}/output_0", f"{unsqueeze_2_name}/output_0", f"/model/constants/TensorProto.INT64/1D/{self.num_attn_heads // self.num_kv_heads}", f"{unsqueeze_3_name}/output_0", f"{unsqueeze_4_name}/output_0"]
self.make_concat(concat_2_name, concat_2_inputs, dtype=TensorProto.INT64, shape=[5], axis=0)
mul_1_name = f"{basename}/Mul_1"
mul_1_inputs = [f"{unsqueeze_2_name}/output_0", f"/model/constants/TensorProto.INT64/0D/{self.num_attn_heads // self.num_kv_heads}"]
self.make_mul(mul_1_name, mul_1_inputs, dtype=TensorProto.INT64, shape=None)
concat_3_name = f"{basename}/Concat_3"
concat_3_inputs = [f"{unsqueeze_1_name}/output_0", f"{mul_1_name}/output_0", f"{unsqueeze_3_name}/output_0", f"{unsqueeze_4_name}/output_0"]
self.make_concat(concat_3_name, concat_3_inputs, dtype=TensorProto.INT64, shape=[4], axis=0)
# Make the subgraph that follows the initial subgraph
#
# Mul ---> Equal
# / \
# Reshape --> Shape --> ConstantOfShape --> Where
# | |
# +----------------------------------------+
reshape_2_name = f"{basename}/Reshape_2"
reshape_2_inputs = [f"{concat_2_name}/output_0", "/model/constants/TensorProto.INT64/1D/-1"]
self.make_reshape(reshape_2_name, reshape_2_inputs, dtype=TensorProto.INT64, shape=None)
shape_2_name = f"{basename}/Shape_2"
self.make_shape(shape_2_name, f"{reshape_2_name}/output_0", shape=[1])
constant_shape_name = f"{basename}/ConstantOfShape"
constant_shape_value = numpy_helper.from_array(np.array([1], dtype="int64"))
self.make_constant_of_shape(constant_shape_name, f"{shape_2_name}/output_0", value=constant_shape_value, dtype=TensorProto.INT64, shape=[5])
mul_2_name = f"{basename}/Mul"
mul_2_inputs = [f"{constant_shape_name}/output_0", "/model/constants/TensorProto.INT64/0D/-1"]
self.make_mul(mul_2_name, mul_2_inputs, dtype=TensorProto.INT64, shape=[5])
equal_name = f"{basename}/Equal"
equal_inputs = [f"{reshape_2_name}/output_0", f"{mul_2_name}/output_0"]
self.make_equal(equal_name, equal_inputs, shape=[5])
where_name = f"{basename}/Where"
where_inputs = [f"{equal_name}/output_0", f"{constant_shape_name}/output_0", f"{reshape_2_name}/output_0"]
self.make_where(where_name, where_inputs, dtype=TensorProto.INT64, shape=[5])
# Make the final nodes
#
# Where (from above) Concat (from above)
# \ \
# Unsqueeze --> Expand --> Reshape --> Transpose --> Reshape
unsqueeze_5_name = f"{basename}/Unsqueeze_5"
unsqueeze_5_inputs = [present_kv, "/model/constants/TensorProto.INT64/1D/2"]
self.make_unsqueeze(unsqueeze_5_name, unsqueeze_5_inputs, dtype=self.io_dtype, shape=['batch_size', self.num_kv_heads, 1, 'sequence_length', self.head_size])
expand_name = f"{basename}/Expand"
expand_inputs = [f"{unsqueeze_5_name}/output_0", f"{where_name}/output_0"]
self.make_expand(expand_name, expand_inputs, dtype=self.io_dtype, shape=['batch_size', self.num_kv_heads, self.num_attn_heads // self.num_kv_heads, 'sequence_length', self.head_size])
reshape_3_name = f"{basename}/Reshape_3"
reshape_3_inputs = [f"{expand_name}/output_0", f"{concat_3_name}/output_0"]
self.make_reshape(reshape_3_name, reshape_3_inputs, dtype=self.io_dtype, shape=['batch_size', self.num_attn_heads, 'sequence_length', self.head_size])
transpose_2_name = f"{basename}/Transpose_2"
transpose_2_input = f"{reshape_3_name}/output_0"
self.make_transpose(transpose_2_name, transpose_2_input, dtype=self.io_dtype, shape=['batch_size', 'sequence_length', self.num_attn_heads, self.head_size], perm=[0,2,1,3])
reshape_4_name = f"{basename}/Reshape_4"
reshape_4_inputs = [f"{transpose_2_name}/output_0", f"/model/constants/TensorProto.INT64/1D/0, 0, {self.num_attn_heads * self.head_size}"]
self.make_reshape(reshape_4_name, reshape_4_inputs, dtype=self.io_dtype, shape=['batch_size', 'sequence_length', self.num_attn_heads * self.head_size])
input_to_attention = f"{reshape_4_name}/output_0"
return input_to_attention
def make_attention_op(self, name, **kwargs):
op_type = self.attention_attrs["op_type"]
if op_type == "MultiHeadAttention":
self.make_multi_head_attention(name, add_qk=f"{self.mask_attrs['mask_name']}/output_0", **kwargs)
elif op_type == "GroupQueryAttention":
self.make_group_query_attention(name, seqlens_k=f"{self.mask_attrs['seqlens_k']}/output_0", total_seq_len=f"{self.mask_attrs['total_seq_len']}/output_0", **kwargs)
else:
raise NotImplementedError(f"The {op_type} op is not currently supported.")
def make_multi_head_attention(self, name, **kwargs):
inputs = [
kwargs["q_path"], kwargs["k_path"], kwargs["v_path"], kwargs.get("bias", ""),
kwargs.get("attn_mask", ""), kwargs.get("add_qk", ""),
kwargs.get("past_k", ""), kwargs.get("past_v", ""),
]
output = f"{name}/output_0"
outputs = [output, kwargs.get("present_k", ""), kwargs.get("present_v", "")]
self.make_node(
"MultiHeadAttention", inputs=inputs, outputs=outputs, name=name, domain="com.microsoft",
num_heads=self.num_attn_heads, scale=self.attention_attrs["scale"],
)
self.make_value_info(output, self.io_dtype, shape=['batch_size', 'sequence_length', self.head_size * self.num_attn_heads])
def make_group_query_attention(self, name, **kwargs):
inputs = [
kwargs["q_path"], kwargs["k_path"], kwargs["v_path"],
kwargs.get("past_k", ""), kwargs.get("past_v", ""),
kwargs.get("seqlens_k", ""), kwargs.get("total_seq_len", ""),
kwargs.get("cos_cache", ""), kwargs.get("sin_cache", ""),
]
output = f"{name}/output_0"
outputs = [output, kwargs.get("present_k", ""), kwargs.get("present_v", "")]
self.make_node(
"GroupQueryAttention", inputs=inputs, outputs=outputs, name=name, domain="com.microsoft",
num_heads=self.num_attn_heads, kv_num_heads=self.num_kv_heads, scale=self.attention_attrs["scale"], # local_window_size=self.window_size, # Disable sliding window attribute temporarily
do_rotary=self.attention_attrs["use_rotemb_in_attn"], rotary_interleaved=self.rotemb_attrs["interleaved"],
)
self.make_value_info(output, self.io_dtype, shape=['batch_size', 'sequence_length', self.head_size * self.num_attn_heads])
def make_attention(self, layer_id, attention, root_input, **kwargs):
# Make nodes for the Attention subgraph
#
# MultiHeadAttention example:
#
# root_input
# / | \
# Q_MatMul K_MatMul V_MatMul 4D causal mask past_key past_value
# | | | | | |
# Q_Add K_Add V_Add +------------+-----------+
# | | | |
# Q_Rotary K_Rotary | |
# \ | / |
# MultiHeadAttention--------------------------+
# |
# O_MatMul
# |
# O_Add
#
# GroupQueryAttention example:
#
# root_input
# / | \
# Q_MatMul K_MatMul V_MatMul seqlens_k total_seq_len past_key past_value
# | | | | | | |
# Q_Add K_Add V_Add +------------+-----------+----------+
# | | | |
# Q_Rotary K_Rotary | |
# \ | / |
# GroupQueryAttention-----------------------+
# |
# O_MatMul
# |
# O_Add
q_input_to_attention = ""
k_input_to_attention = ""
v_input_to_attention = ""
# Make MatMul nodes
if self.attention_attrs["use_packed_matmul"]:
# Combine 3 MatMuls into 1 packed MatMul
qkv_matmul_name = f"/model/layers.{layer_id}/attn/qkv_proj/MatMul"
self.make_packed_matmul(attention.q_proj.weight.detach().numpy(), attention.k_proj.weight.detach().numpy(), attention.v_proj.weight.detach().numpy(), qkv_matmul_name, root_input)
q_input_to_attention = f"{qkv_matmul_name}/output_0"
else:
q_matmul_name = f"/model/layers.{layer_id}/attn/q_proj/MatMul"
self.make_matmul(attention.q_proj.weight.detach().numpy(), q_matmul_name, root_input)
q_input_to_attention = f"{q_matmul_name}/output_0"
k_matmul_name = f"/model/layers.{layer_id}/attn/k_proj/MatMul"
self.make_matmul(attention.k_proj.weight.detach().numpy(), k_matmul_name, root_input)
k_input_to_attention = f"{k_matmul_name}/output_0"
v_matmul_name = f"/model/layers.{layer_id}/attn/v_proj/MatMul"
self.make_matmul(attention.v_proj.weight.detach().numpy(), v_matmul_name, root_input)
v_input_to_attention = f"{v_matmul_name}/output_0"
# Make Add nodes (if bias exists)
q_bias_exists = attention.q_proj.bias is not None
k_bias_exists = attention.k_proj.bias is not None
v_bias_exists = attention.v_proj.bias is not None
all_bias_exists = q_bias_exists and k_bias_exists and v_bias_exists
if all_bias_exists and self.attention_attrs["use_packed_matmul"]:
# Combine 3 Adds into 1 packed Add
qkv_add_name = f"/model/layers.{layer_id}/attn/qkv_proj/Add"
self.make_packed_add(attention.q_proj.bias.detach().numpy(), attention.k_proj.bias.detach().numpy(), attention.v_proj.bias.detach().numpy(), qkv_add_name, root_input=q_input_to_attention)
q_input_to_attention = f"{qkv_add_name}/output_0"
else:
if q_bias_exists:
q_add_name = f"/model/layers.{layer_id}/attn/q_proj/Add"
self.make_add_bias(attention.q_proj.bias.detach().numpy(), q_add_name, root_input=q_input_to_attention)
q_input_to_attention = f"{q_add_name}/output_0"
if k_bias_exists:
k_add_name = f"/model/layers.{layer_id}/attn/k_proj/Add"
self.make_add_bias(attention.k_proj.bias.detach().numpy(), k_add_name, root_input=k_input_to_attention)
k_input_to_attention = f"{k_add_name}/output_0"
if v_bias_exists:
v_add_name = f"/model/layers.{layer_id}/attn/v_proj/Add"
self.make_add_bias(attention.v_proj.bias.detach().numpy(), v_add_name, root_input=v_input_to_attention)
v_input_to_attention = f"{v_add_name}/output_0"
# Make RotaryEmbedding nodes
cos_cache_name, sin_cache_name = "", ""
if self.attention_attrs["use_rotemb_in_attn"]:
cos_cache_name, sin_cache_name = self.make_rotary_embedding_caches(attention.rotary_emb)
else:
q_rotary_name = f"/model/layers.{layer_id}/attn/q_rotary/RotaryEmbedding"
self.make_rotary_embedding(attention.rotary_emb, q_rotary_name, root_input=q_input_to_attention, position_ids=kwargs.get("position_ids", "position_ids"))
q_input_to_attention = f"{q_rotary_name}/output_0"
k_rotary_name = f"/model/layers.{layer_id}/attn/k_rotary/RotaryEmbedding"