Upload export.py
Browse files
export.py
ADDED
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
from itertools import chain
|
3 |
+
|
4 |
+
import torch
|
5 |
+
import torch.nn as nn
|
6 |
+
from transformers import LlamaConfig, DynamicCache
|
7 |
+
|
8 |
+
from midi_model import MIDIModel, config_name_list, MIDIModelConfig
|
9 |
+
|
10 |
+
|
11 |
+
class MIDIModelBase(nn.Module):
|
12 |
+
def __init__(self, model):
|
13 |
+
super().__init__()
|
14 |
+
self.net = model.net
|
15 |
+
|
16 |
+
def forward(self, x, past_kv):
|
17 |
+
cache = DynamicCache.from_legacy_cache(past_kv)
|
18 |
+
x = self.net.embed_tokens(x)
|
19 |
+
x = x.sum(dim=-2)
|
20 |
+
x = self.net.forward(inputs_embeds=x,
|
21 |
+
past_key_values=cache,
|
22 |
+
use_cache=True)
|
23 |
+
return x.last_hidden_state, cache.to_legacy_cache()
|
24 |
+
|
25 |
+
|
26 |
+
class MIDIModelToken(nn.Module):
|
27 |
+
def __init__(self, model):
|
28 |
+
super().__init__()
|
29 |
+
self.net_token = model.net_token
|
30 |
+
self.lm_head = model.lm_head
|
31 |
+
|
32 |
+
def forward(self, hidden_state, x, past_kv):
|
33 |
+
cache = DynamicCache.from_legacy_cache(past_kv)
|
34 |
+
x = self.net_token.embed_tokens(x)
|
35 |
+
x = torch.cat([hidden_state, x], dim=1)
|
36 |
+
hidden_state = x
|
37 |
+
hidden_state = self.net_token.forward(inputs_embeds=hidden_state,
|
38 |
+
past_key_values=cache,
|
39 |
+
use_cache=True).last_hidden_state
|
40 |
+
return self.lm_head(hidden_state), cache.to_legacy_cache()
|
41 |
+
|
42 |
+
|
43 |
+
def export_onnx(model, model_inputs, input_names, output_names, dynamic_axes, meta_data, path):
|
44 |
+
import onnx
|
45 |
+
from onnxsim import simplify
|
46 |
+
torch.onnx.export(model, # model being run
|
47 |
+
model_inputs, # model input (or a tuple for multiple inputs)
|
48 |
+
path, # where to save the model (can be a file or file-like object)
|
49 |
+
export_params=True, # store the trained parameter weights inside the model file
|
50 |
+
opset_version=14, # the ONNX version to export the model to
|
51 |
+
do_constant_folding=True, # whether to execute constant folding for optimization
|
52 |
+
input_names=input_names, # the model's input names
|
53 |
+
output_names=output_names, # the model's output names
|
54 |
+
verbose=True,
|
55 |
+
dynamic_axes=dynamic_axes
|
56 |
+
)
|
57 |
+
onnx_model = onnx.load(path)
|
58 |
+
model_simp, check = simplify(onnx_model)
|
59 |
+
assert check, "Simplified ONNX model could not be validated"
|
60 |
+
for k, v in meta_data.items():
|
61 |
+
meta = model_simp.metadata_props.add()
|
62 |
+
meta.key, meta.value = k, str(v)
|
63 |
+
onnx.save(model_simp, path)
|
64 |
+
print('finished exporting onnx')
|
65 |
+
|
66 |
+
|
67 |
+
def get_past_kv(config: LlamaConfig, batch_size=1, past_seq_len=16, torch_dtype= torch.float32, device="cpu"):
|
68 |
+
head_size = config.hidden_size // config.num_attention_heads
|
69 |
+
past_kv = [
|
70 |
+
(
|
71 |
+
torch.rand(batch_size, config.num_attention_heads,
|
72 |
+
past_seq_len, head_size, dtype=torch_dtype, device=device),
|
73 |
+
torch.rand(batch_size, config.num_attention_heads,
|
74 |
+
past_seq_len, head_size, dtype=torch_dtype, device=device),
|
75 |
+
)
|
76 |
+
for _ in range(config.num_hidden_layers)
|
77 |
+
]
|
78 |
+
input_names = list(
|
79 |
+
chain.from_iterable(
|
80 |
+
(f"past_key_values.{i}.key", f"past_key_values.{i}.value") for i in
|
81 |
+
range(config.num_hidden_layers)
|
82 |
+
)
|
83 |
+
)
|
84 |
+
output_names = list(
|
85 |
+
chain.from_iterable((f"present.{i}.key", f"present.{i}.value") for i in range(config.num_hidden_layers))
|
86 |
+
)
|
87 |
+
return past_kv, input_names, output_names
|
88 |
+
|
89 |
+
|
90 |
+
if __name__ == '__main__':
|
91 |
+
parser = argparse.ArgumentParser()
|
92 |
+
parser.add_argument(
|
93 |
+
"--ckpt", type=str, default="model.ckpt", help="load ckpt"
|
94 |
+
)
|
95 |
+
parser.add_argument(
|
96 |
+
"--config", type=str, default="tv2o-medium", choices=config_name_list, help="model config"
|
97 |
+
)
|
98 |
+
parser.add_argument(
|
99 |
+
"--lora", type=str, default="", help="load lora"
|
100 |
+
)
|
101 |
+
parser.add_argument(
|
102 |
+
"--model-base-out", type=str, default="model_base.onnx", help="model base output path"
|
103 |
+
)
|
104 |
+
parser.add_argument(
|
105 |
+
"--model-token-out", type=str, default="model_token.onnx", help="model token output path"
|
106 |
+
)
|
107 |
+
opt = parser.parse_args()
|
108 |
+
config = MIDIModelConfig.from_name(opt.config)
|
109 |
+
tokenizer = config.tokenizer
|
110 |
+
model = MIDIModel(config).to(device="cpu")
|
111 |
+
ckpt = torch.load(opt.ckpt, map_location="cpu")
|
112 |
+
state_dict = ckpt.get("state_dict", ckpt)
|
113 |
+
model.load_state_dict(state_dict, strict=False)
|
114 |
+
if opt.lora != "":
|
115 |
+
model.load_merge_lora(opt.lora)
|
116 |
+
model.eval()
|
117 |
+
model_base = MIDIModelBase(model).eval()
|
118 |
+
model_token = MIDIModelToken(model).eval()
|
119 |
+
meta_data = {"config_name": opt.config, "config": config}
|
120 |
+
past_kv_shape = {0: "batch", 2: "past_seq"}
|
121 |
+
present_kv_shape = {0: "batch", 2: "present_seq"}
|
122 |
+
with torch.no_grad():
|
123 |
+
dynamic_axes = {
|
124 |
+
"x": {0: "batch", 1: "mid_seq", 2: "token_seq"},
|
125 |
+
"hidden": {0: "batch", 1: "mid_seq"}
|
126 |
+
}
|
127 |
+
x = torch.randint(tokenizer.vocab_size, (1, 16, tokenizer.max_token_seq), dtype=torch.int64, device="cpu")
|
128 |
+
past_kv, input_names, output_names= get_past_kv(config.net_config, past_seq_len=16,
|
129 |
+
torch_dtype=torch.float32)
|
130 |
+
for name in input_names:
|
131 |
+
dynamic_axes[name] = past_kv_shape
|
132 |
+
for name in output_names:
|
133 |
+
dynamic_axes[name] = present_kv_shape
|
134 |
+
input_names = [ "x"] + input_names
|
135 |
+
output_names = ["hidden"] + output_names
|
136 |
+
export_onnx(model_base, (x, past_kv),
|
137 |
+
input_names, output_names, dynamic_axes, meta_data, opt.model_base_out)
|
138 |
+
|
139 |
+
dynamic_axes = {
|
140 |
+
"x": {0: "batch", 1: "token_seq"},
|
141 |
+
"hidden": {0: "batch", 1: "states"},
|
142 |
+
"y": {0: "batch", 1: "token_seq1"}
|
143 |
+
}
|
144 |
+
hidden = torch.randn(1, 1, config.n_embd, device="cpu")
|
145 |
+
x = torch.randint(tokenizer.vocab_size, (1, tokenizer.max_token_seq //2), dtype=torch.int64, device="cpu")
|
146 |
+
past_kv, input_names, output_names = get_past_kv(config.net_token_config,
|
147 |
+
past_seq_len=(tokenizer.max_token_seq // 2),
|
148 |
+
torch_dtype=torch.float32)
|
149 |
+
for name in input_names:
|
150 |
+
dynamic_axes[name] = past_kv_shape
|
151 |
+
for name in output_names:
|
152 |
+
dynamic_axes[name] = present_kv_shape
|
153 |
+
input_names = ["hidden", "x"] + input_names
|
154 |
+
output_names = ["y"] + output_names
|
155 |
+
export_onnx(model_token, (hidden, x, past_kv),
|
156 |
+
input_names, output_names, dynamic_axes, meta_data, opt.model_token_out)
|