English
music
JoshuaW1997 commited on
Commit
bd2d17d
1 Parent(s): 3f2df17

Upload 12 files

Browse files
Files changed (12) hide show
  1. captioning.py +88 -0
  2. cli_inference.py +56 -0
  3. dataset.py +124 -0
  4. evaluation.py +76 -0
  5. llama_flash_attn_monkey_patch.py +124 -0
  6. model.py +317 -0
  7. modeling_llama.py +885 -0
  8. salmonn_trainer.py +35 -0
  9. train.json +27 -0
  10. train_mem.py +14 -0
  11. trainer.py +81 -0
  12. utils.py +12 -0
captioning.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (2023) Tsinghua University, Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import torch
17
+ import argparse
18
+ import json
19
+ import pandas as pd
20
+ import copy
21
+ import numpy as np
22
+ from tqdm import tqdm
23
+ from model import SALMONN
24
+
25
+ if __name__ == "__main__":
26
+
27
+ parser = argparse.ArgumentParser()
28
+ parser.add_argument("--device", type=str, default="cuda")
29
+ parser.add_argument("--ckpt_path", type=str, default='./salomnn_7b.bin')
30
+ parser.add_argument("--whisper_path", type=str, default='whisper-large-v2')
31
+ parser.add_argument("--beats_path", type=str, default='BEATs_iter3_plus_AS2M_finetuned_on_AS2M_cpt2.pt')
32
+ parser.add_argument("--vicuna_path", type=str, default='vicuna-7b-v1.5')
33
+ parser.add_argument("--audio_path", type=str, default='./Harmonixset/music_data')
34
+ parser.add_argument("--meta_path", type=str, default='./Harmonixset/metadata.csv')
35
+ parser.add_argument("--segment_path", type=str, default='./Harmonixset/segments')
36
+ parser.add_argument("--caption_path", type=str, default='./Harmonixset/captions')
37
+ parser.add_argument("--low_resource", action='store_true', default=False)
38
+ parser.add_argument("--debug", action="store_true", default=False)
39
+
40
+ args = parser.parse_args()
41
+
42
+ os.makedirs(args.caption_path, exist_ok=True)
43
+ meta = pd.read_csv(args.meta_path, header=0)[['File', 'BPM', 'Genre']]
44
+ samples = []
45
+ for i, row in meta.iterrows():
46
+ fname = row['File']
47
+ sample = row.to_dict()
48
+ sample['audio'] = f'{args.audio_path}/{fname}.wav'
49
+ sample['segment'] = f'{args.segment_path}/{fname}.txt'
50
+ if os.path.exists(sample['audio']) and os.path.exists(sample['segment']):
51
+ samples.append(sample)
52
+
53
+
54
+ model = SALMONN(
55
+ ckpt=args.ckpt_path,
56
+ whisper_path=args.whisper_path,
57
+ beats_path=args.beats_path,
58
+ vicuna_path=args.vicuna_path
59
+ ).to(torch.float16).cuda()
60
+ model.eval()
61
+
62
+ # prompt_tmp = 'Please describe functional music segments and their time boundaries. In each segment, describe the musical change of each segment and provide detailed analysis.'
63
+ # prompt_tmp = 'First describe the music in general in terms of mood, theme, tempo, melody, instruments and chord progression. Then provide a detailed music analysis by describing each functional segment and its time boundaries.'
64
+ prompt_tmp = 'This is a {genre} music of {bpm} beat-per-minute (BPM). First describe the music in general in terms of mood, theme, tempo, melody, instruments and chord progression. Then provide a detailed music analysis by describing each functional segment and its time boundaries. Please note that the music boundaries are {segments}.'
65
+
66
+ with torch.cuda.amp.autocast(dtype=torch.float16):
67
+ for sample in tqdm(samples):
68
+ fname = sample['File']
69
+ if os.path.exists(f'{args.caption_path}/{fname}.json'):
70
+ continue
71
+ # try:
72
+ wav_path = sample['audio']
73
+ ts, tag = zip(*[line.split(' ') for line in open(sample['segment']) if 'silence' not in line and line.strip()])
74
+ ts = np.asarray([float(t) for t in ts])
75
+ bdr = (ts[0], ts[-1])
76
+ ts = (ts - ts[0]) / (ts[-1] - ts[0])
77
+ ts = [np.round(t * 100) for t in ts]
78
+
79
+ prompt = prompt_tmp.format(genre=sample['Genre'], bpm=sample['BPM'], segments=ts)
80
+
81
+ save_sample = copy.deepcopy(sample)
82
+ captions = model.generate(wav_path, prompt=prompt, bdr=bdr, repetition_penalty=1.5, num_return_sequences=5, num_beams=10)
83
+ save_sample['tags'] = tag
84
+ save_sample['ts'] = ts
85
+ save_sample['captions'] = captions
86
+ json.dump(save_sample, open(f'{args.caption_path}/{fname}.json', 'w'))
87
+ # except Exception as e:
88
+ # print(e)
cli_inference.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (2023) Tsinghua University, Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import torch
16
+ import argparse
17
+ from model import SALMONN
18
+
19
+ if __name__ == "__main__":
20
+
21
+ parser = argparse.ArgumentParser()
22
+ parser.add_argument("--device", type=str, default="cuda")
23
+ parser.add_argument("--ckpt_path", type=str, default='./salomnn_7b.bin')
24
+ parser.add_argument("--whisper_path", type=str, default='whisper-large-v2')
25
+ parser.add_argument("--beats_path", type=str, default='BEATs_iter3_plus_AS2M_finetuned_on_AS2M_cpt2.pt')
26
+ parser.add_argument("--vicuna_path", type=str, default='vicuna-7b-v1.5')
27
+ parser.add_argument("--low_resource", action='store_true', default=False)
28
+ parser.add_argument("--debug", action="store_true", default=False)
29
+
30
+ args = parser.parse_args()
31
+
32
+ model = SALMONN(
33
+ ckpt=args.ckpt_path,
34
+ whisper_path=args.whisper_path,
35
+ beats_path=args.beats_path,
36
+ vicuna_path=args.vicuna_path
37
+ ).to(torch.float16).cuda()
38
+
39
+ prompt = 'First describe the music in general in terms of mood, theme, tempo, melody, instruments and chord progression. Then provide a detailed music analysis by describing each functional segment and its time boundaries.'
40
+ prompt_tmp = 'This is a Pop music of 69 beat-per-minute (BPM). First describe the music in general in terms of mood, theme, tempo, melody, instruments and chord progression. Then provide a detailed music analysis by describing each functional segment and its time boundaries. Please note that the music boundaries are [0, 41, 58, 83, 100].'
41
+ model.eval()
42
+ while True:
43
+ print("=====================================")
44
+ wav_path = input("Your Wav Path:\n")
45
+ prompt = input("Your Prompt:\n")
46
+ try:
47
+ print("Output:")
48
+ # for environment with cuda>=117
49
+ with torch.cuda.amp.autocast(dtype=torch.float16):
50
+ print(model.generate(wav_path, prompt=prompt, repetition_penalty=1.5, num_beams=10, top_p=.7, temperature=.2)[0])
51
+ except Exception as e:
52
+ print(e)
53
+ if args.debug:
54
+ import pdb
55
+
56
+ pdb.set_trace()
dataset.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import copy
3
+ import json
4
+ import torch
5
+ import transformers
6
+ import numpy as np
7
+ import pickle as pkl
8
+ from torch.utils.data import Dataset
9
+ from dataclasses import dataclass, field
10
+ from typing import Dict, Optional, Sequence, List
11
+
12
+ IGNORE_INDEX = -100
13
+ MAX_LENGTH = 2048
14
+
15
+
16
+ @dataclass
17
+ class DataArguments:
18
+ data_path: str = field(default='./MusicCaps', metadata={"help": "Path to the training data."})
19
+ feat_folder: Optional[str] = field(default='./MusicCaps/music_feat')
20
+
21
+ def preprocess_v1(sources: str, tokenizer: transformers.PreTrainedTokenizer, metadata,
22
+ prompt_pattern="USER: <Speech><SpeechHere></Speech> Describe the music in detail.\nASSISTANT:\n") -> Dict:
23
+ sources = sources.split('\n')
24
+ clips, duration, caption = metadata['clips'], metadata['duration'], []
25
+ length = 0
26
+ for l, c in zip(clips, sources):
27
+ caption.append(
28
+ f'From {int(length / duration * 100)} to {int((length + l) / duration * 100)},'
29
+ + ','.join(c.split(',')[1:])
30
+ )
31
+ length += l
32
+
33
+ targets = prompt_pattern + '\n'.join(caption)
34
+
35
+ targets_left, targets_right = targets.split('<SpeechHere>')
36
+ targets_right = tokenizer(targets_right, return_tensors="pt", add_special_tokens=False).input_ids[0]
37
+
38
+ sources_left, sources_right = prompt_pattern.split('<SpeechHere>')
39
+ sources_left = tokenizer(sources_left, return_tensors="pt", add_special_tokens=False).input_ids[0]
40
+ sources_right_length = tokenizer(sources_right, return_tensors="pt", add_special_tokens=False).input_ids.shape[-1]
41
+
42
+ sources_right = copy.deepcopy(targets_right)
43
+
44
+ targets_left = torch.LongTensor([IGNORE_INDEX] * len(sources_left))
45
+ targets_right[:sources_right_length] = IGNORE_INDEX
46
+
47
+ sources_right, targets_right = sources_right[:MAX_LENGTH], targets_right[:MAX_LENGTH]
48
+
49
+ return dict(input_ids=(sources_left, sources_right), labels=(targets_left, targets_right))
50
+
51
+
52
+ def preprocess(sources: str, tokenizer: transformers.PreTrainedTokenizer, metadata,
53
+ prompt_pattern="USER: <Speech><SpeechHere></Speech> Describe the music in detail.\nASSISTANT:\n") -> Dict:
54
+ targets = prompt_pattern + sources
55
+
56
+ targets_left, targets_right = targets.split('<SpeechHere>')
57
+ targets_right = tokenizer(targets_right, return_tensors="pt", add_special_tokens=False).input_ids[0]
58
+
59
+ sources_left, sources_right = prompt_pattern.split('<SpeechHere>')
60
+ sources_left = tokenizer(sources_left, return_tensors="pt", add_special_tokens=False).input_ids[0]
61
+ sources_right_length = tokenizer(sources_right, return_tensors="pt", add_special_tokens=False).input_ids.shape[-1]
62
+
63
+ sources_right = copy.deepcopy(targets_right)
64
+
65
+ targets_left = torch.LongTensor([IGNORE_INDEX] * len(sources_left))
66
+ targets_right[:sources_right_length] = IGNORE_INDEX
67
+
68
+ sources_right, targets_right = sources_right[:MAX_LENGTH], targets_right[:MAX_LENGTH]
69
+
70
+ return dict(input_ids=(sources_left, sources_right), labels=(targets_left, targets_right))
71
+
72
+
73
+ class LazySupervisedDataset(Dataset):
74
+ """Dataset for supervised fine-tuning."""
75
+
76
+ def __init__(self, data_path, tokenizer, data_args):
77
+ super(LazySupervisedDataset, self).__init__()
78
+
79
+ self.tokenizer = tokenizer
80
+ self.list_data_dict = json.load(open(data_path, "r"))
81
+ self.data_args = data_args
82
+
83
+ def __len__(self):
84
+ return len(self.list_data_dict)
85
+
86
+ def __getitem__(self, i):
87
+ source = copy.deepcopy(self.list_data_dict[i])
88
+
89
+ feature_path = '{}/{}.pkl'.format(self.data_args.feat_folder, source['id']) # Added
90
+ music = pkl.load(open(feature_path, 'rb')) # <N, 768> float16
91
+ speech = torch.from_numpy(music['speech'])
92
+ audio = torch.from_numpy(music['audio'])
93
+
94
+ captions = source['caption']
95
+ if not isinstance(captions, str):
96
+ weights = np.asarray([len(c) for c in captions])
97
+ weights = weights / weights.sum()
98
+ captions = random.choices(captions, weights, k=1)[0]
99
+
100
+ data_dict = preprocess(captions, self.tokenizer, source['meta'])
101
+
102
+ data_dict['speeches'] = speech
103
+ data_dict['audios'] = audio
104
+ return data_dict
105
+
106
+
107
+ @dataclass
108
+ class DataCollatorForSupervisedDataset(object):
109
+ """Collate examples for supervised fine-tuning."""
110
+
111
+ tokenizer: transformers.PreTrainedTokenizer
112
+
113
+ def __call__(self, instances):
114
+ input_ids, labels, speeches, audios = tuple(
115
+ [instance[key] for instance in instances] for key in ("input_ids", "labels", "speeches", "audios"))
116
+ batch = dict(input_ids=input_ids, labels=labels, speeches=speeches, audios=audios)
117
+ return batch
118
+
119
+
120
+ def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, data_args) -> Dict:
121
+ """Make dataset and collator for supervised fine-tuning."""
122
+ train_dataset = LazySupervisedDataset(tokenizer=tokenizer, data_path=data_args.data_path, data_args=data_args)
123
+ data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
124
+ return dict(train_dataset=train_dataset, eval_dataset=None, data_collator=data_collator)
evaluation.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (2023) Tsinghua University, Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import torch
17
+ import argparse
18
+ import json
19
+ import pandas as pd
20
+ import copy
21
+ import numpy as np
22
+ from tqdm import tqdm
23
+ from model import SALMONN
24
+
25
+ if __name__ == "__main__":
26
+
27
+ parser = argparse.ArgumentParser()
28
+ parser.add_argument("--device", type=str, default="cuda")
29
+ parser.add_argument("--ckpt_path", type=str, default='./salomnn_7b.bin')
30
+ parser.add_argument("--whisper_path", type=str, default='whisper-large-v2')
31
+ parser.add_argument("--beats_path", type=str, default='BEATs_iter3_plus_AS2M_finetuned_on_AS2M_cpt2.pt')
32
+ parser.add_argument("--vicuna_path", type=str, default='vicuna-7b-v1.5')
33
+ parser.add_argument("--audio_path", type=str, default='./Harmonixset/music_data')
34
+ parser.add_argument("--caption_path", type=str, default='./Harmonixset/captions')
35
+ parser.add_argument("--start", type=int, default=0)
36
+ parser.add_argument("--end", type=int, default=10000)
37
+ parser.add_argument("--low_resource", action='store_true', default=False)
38
+ parser.add_argument("--debug", action="store_true", default=False)
39
+
40
+ args = parser.parse_args()
41
+
42
+ os.makedirs(args.caption_path, exist_ok=True)
43
+
44
+ model = SALMONN(
45
+ ckpt=args.ckpt_path,
46
+ whisper_path=args.whisper_path,
47
+ beats_path=args.beats_path,
48
+ vicuna_path=args.vicuna_path
49
+ ).to(torch.float16).cuda()
50
+ model.eval()
51
+
52
+ prompt_tmp = 'First describe the music in general in terms of mood, theme, tempo, melody, instruments and chord progression. Then provide a detailed music analysis by describing each functional segment and its time boundaries.'
53
+
54
+ sample_list = os.listdir(args.audio_path)[args.start:args.end]
55
+ with torch.cuda.amp.autocast(dtype=torch.float16):
56
+ for sample in tqdm(sample_list):
57
+ if os.path.exists(f'{args.caption_path}/{sample}.json'):
58
+ continue
59
+ try:
60
+ wav_path = f'{args.audio_path}/{sample}'
61
+ prompt = prompt_tmp
62
+ save_sample = {'wav_path': sample}
63
+ captions = model.generate(
64
+ wav_path,
65
+ prompt=prompt,
66
+ bdr=(0, 180),
67
+ repetition_penalty=1.5,
68
+ num_return_sequences=1,
69
+ num_beams=5,
70
+ top_p=0.95,
71
+ top_k=50,
72
+ )
73
+ save_sample['captions'] = captions
74
+ json.dump(save_sample, open(f'{args.caption_path}/{sample}.json', 'w'))
75
+ except Exception as e:
76
+ print(e)
llama_flash_attn_monkey_patch.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional, Tuple
2
+ import logging
3
+
4
+ import torch
5
+ from torch import nn
6
+
7
+ import transformers
8
+ from transformers.models.llama.modeling_llama import apply_rotary_pos_emb
9
+
10
+ from einops import rearrange
11
+
12
+ try:
13
+ from flash_attn.flash_attn_interface import flash_attn_unpadded_qkvpacked_func
14
+ except ImportError:
15
+ from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func
16
+ from flash_attn.bert_padding import unpad_input, pad_input
17
+
18
+
19
+ def forward(
20
+ self,
21
+ hidden_states: torch.Tensor,
22
+ attention_mask: Optional[torch.Tensor] = None,
23
+ position_ids: Optional[torch.Tensor] = None,
24
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
25
+ output_attentions: bool = False,
26
+ use_cache: bool = False,
27
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
28
+ """Input shape: Batch x Time x Channel
29
+
30
+ attention_mask: [bsz, q_len]
31
+ """
32
+ bsz, q_len, _ = hidden_states.size()
33
+
34
+ query_states = (
35
+ self.q_proj(hidden_states)
36
+ .view(bsz, q_len, self.num_heads, self.head_dim)
37
+ .transpose(1, 2)
38
+ )
39
+ key_states = (
40
+ self.k_proj(hidden_states)
41
+ .view(bsz, q_len, self.num_heads, self.head_dim)
42
+ .transpose(1, 2)
43
+ )
44
+ value_states = (
45
+ self.v_proj(hidden_states)
46
+ .view(bsz, q_len, self.num_heads, self.head_dim)
47
+ .transpose(1, 2)
48
+ )
49
+ # [bsz, q_len, nh, hd]
50
+ # [bsz, nh, q_len, hd]
51
+
52
+ kv_seq_len = key_states.shape[-2]
53
+ assert past_key_value is None, "past_key_value is not supported"
54
+
55
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
56
+ query_states, key_states = apply_rotary_pos_emb(
57
+ query_states, key_states, cos, sin, position_ids
58
+ )
59
+ # [bsz, nh, t, hd]
60
+ assert not output_attentions, "output_attentions is not supported"
61
+ assert not use_cache, "use_cache is not supported"
62
+
63
+ # Flash attention codes from
64
+ # https://github.com/HazyResearch/flash-attention/blob/main/flash_attn/flash_attention.py
65
+
66
+ # transform the data into the format required by flash attention
67
+ qkv = torch.stack(
68
+ [query_states, key_states, value_states], dim=2
69
+ ) # [bsz, nh, 3, q_len, hd]
70
+ qkv = qkv.transpose(1, 3) # [bsz, q_len, 3, nh, hd]
71
+ # We have disabled _prepare_decoder_attention_mask in LlamaModel
72
+ # the attention_mask should be the same as the key_padding_mask
73
+ key_padding_mask = attention_mask
74
+
75
+ if key_padding_mask is None:
76
+ qkv = rearrange(qkv, "b s ... -> (b s) ...")
77
+ max_s = q_len
78
+ cu_q_lens = torch.arange(
79
+ 0, (bsz + 1) * q_len, step=q_len, dtype=torch.int32, device=qkv.device
80
+ )
81
+ output = flash_attn_unpadded_qkvpacked_func(
82
+ qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True
83
+ )
84
+ output = rearrange(output, "(b s) ... -> b s ...", b=bsz)
85
+ else:
86
+ nheads = qkv.shape[-2]
87
+ x = rearrange(qkv, "b s three h d -> b s (three h d)")
88
+ x_unpad, indices, cu_q_lens, max_s = unpad_input(x, key_padding_mask)
89
+ x_unpad = rearrange(
90
+ x_unpad, "nnz (three h d) -> nnz three h d", three=3, h=nheads
91
+ )
92
+ output_unpad = flash_attn_unpadded_qkvpacked_func(
93
+ x_unpad, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True
94
+ )
95
+ output = rearrange(
96
+ pad_input(
97
+ rearrange(output_unpad, "nnz h d -> nnz (h d)"), indices, bsz, q_len
98
+ ),
99
+ "b s (h d) -> b s h d",
100
+ h=nheads,
101
+ )
102
+ return self.o_proj(rearrange(output, "b s h d -> b s (h d)")), None, None
103
+
104
+
105
+ # Disable the transformation of the attention mask in LlamaModel as the flash attention
106
+ # requires the attention mask to be the same as the key_padding_mask
107
+ def _prepare_decoder_attention_mask(
108
+ self, attention_mask, input_shape, inputs_embeds, past_key_values_length
109
+ ):
110
+ # [bsz, seq_len]
111
+ return attention_mask
112
+
113
+
114
+ def replace_llama_attn_with_flash_attn():
115
+ cuda_major, cuda_minor = torch.cuda.get_device_capability()
116
+ if cuda_major < 8:
117
+ logging.warning(
118
+ "Flash attention is only supported on A100 or H100 GPU during training due to head dim > 64 backward."
119
+ "ref: https://github.com/HazyResearch/flash-attention/issues/190#issuecomment-1523359593"
120
+ )
121
+ transformers.models.llama.modeling_llama.LlamaModel._prepare_decoder_attention_mask = (
122
+ _prepare_decoder_attention_mask
123
+ )
124
+ transformers.models.llama.modeling_llama.LlamaAttention.forward = forward
model.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (2023) Tsinghua University, Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ import torch
17
+ import soundfile as sf
18
+ import torch.nn as nn
19
+ import torch.nn.functional as F
20
+ from peft import LoraConfig, TaskType, get_peft_model
21
+ from transformers import (
22
+ WhisperFeatureExtractor,
23
+ WhisperModel,
24
+ # LlamaForCausalLM,
25
+ LlamaTokenizer
26
+ )
27
+ from modeling_llama import LlamaForCausalLM
28
+ import librosa
29
+ from beats.BEATs import BEATsConfig, BEATs
30
+ from qformer.Qformer import BertConfig, BertLMHeadModel
31
+ from typing import List, Optional, Tuple, Union
32
+
33
+ IGNORE_INDEX = -100
34
+
35
+
36
+ class SALMONN(nn.Module):
37
+ def __init__(self, ckpt, whisper_path, beats_path, vicuna_path,
38
+ speech_qformer_token_num=1, speech_qformer_layer=2,
39
+ lora=True, lora_alpha=32, lora_rank=8, lora_dropout=0.1,
40
+ second_per_frame=0.333333, second_stride=0.333333, compute_dtype=torch.float16):
41
+
42
+ super().__init__()
43
+
44
+ # feature_extractor
45
+ self.feature_extractor = WhisperFeatureExtractor.from_pretrained(whisper_path)
46
+
47
+ # whisper
48
+ self.speech_encoder = WhisperModel.from_pretrained(whisper_path).encoder
49
+ for name, param in self.speech_encoder.named_parameters():
50
+ param.requires_grad = False
51
+ self.ln_speech = nn.LayerNorm(self.speech_encoder.config.d_model)
52
+ print('Whisper model loaded ........')
53
+
54
+ # beats
55
+ self.beats_ckpt = beats_path
56
+ beats_checkpoint = torch.load(self.beats_ckpt, map_location='cpu')
57
+ beats = BEATs(BEATsConfig(beats_checkpoint['cfg']))
58
+ beats.load_state_dict(beats_checkpoint['model'])
59
+ self.beats = beats
60
+ for name, param in self.beats.named_parameters():
61
+ param.requires_grad = False
62
+ self.beats.eval()
63
+ self.ln_audio = nn.LayerNorm(self.beats.cfg.encoder_embed_dim)
64
+ print('Beats model loaded ........')
65
+
66
+ # init speech Qformer
67
+ self.speech_Qformer, self.speech_query_tokens = self.init_speech_Qformer(
68
+ speech_qformer_token_num,
69
+ self.speech_encoder.config.d_model + self.beats.cfg.encoder_embed_dim,
70
+ speech_qformer_layer,
71
+ )
72
+ self.second_per_frame = second_per_frame
73
+ self.second_stride = second_stride
74
+ print('Qformer model initialised ........')
75
+
76
+ # vicuna
77
+ self.llama_model = LlamaForCausalLM.from_pretrained(vicuna_path, torch_dtype=compute_dtype)
78
+ self.config = self.llama_model.config
79
+ print('Vicuna model loaded ........')
80
+
81
+ # lora
82
+ self.lora = lora
83
+ if lora:
84
+ target_modules = None
85
+ self.peft_config = LoraConfig(
86
+ task_type=TaskType.CAUSAL_LM, inference_mode=False, target_modules=target_modules,
87
+ r=lora_rank, lora_alpha=lora_alpha, lora_dropout=lora_dropout,
88
+ )
89
+ self.llama_model = get_peft_model(self.llama_model, self.peft_config)
90
+ print('Added LoRA ........')
91
+
92
+ # tokenizer
93
+ self.tokenizer = LlamaTokenizer.from_pretrained(vicuna_path, use_fast=False)
94
+ self.tokenizer.add_special_tokens({'pad_token': '[PAD]'})
95
+ self.tokenizer.padding_side = "right"
96
+
97
+ # proj
98
+ self.speech_llama_proj = nn.Linear(self.speech_Qformer.config.hidden_size, self.llama_model.config.hidden_size)
99
+
100
+ # load ckpt
101
+ print('Loading Parameters ........')
102
+ ckpt_dict = torch.load(ckpt, map_location='cpu')
103
+ if 'model' in ckpt_dict:
104
+ ckpt_dict = ckpt_dict['model']
105
+ for name, param in ckpt_dict.items():
106
+ if name in self.state_dict():
107
+ print('Loaded:', name)
108
+ self.load_state_dict(ckpt_dict, strict=False)
109
+
110
+ def forward(
111
+ self,
112
+ input_ids, labels, speeches, audios,
113
+ attention_mask: Optional[torch.Tensor] = None,
114
+ position_ids: Optional[torch.LongTensor] = None,
115
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
116
+ inputs_embeds: Optional[torch.FloatTensor] = None,
117
+ use_cache: Optional[bool] = None,
118
+ output_attentions: Optional[bool] = None,
119
+ output_hidden_states: Optional[bool] = None,
120
+ return_dict: Optional[bool] = None,
121
+ ):
122
+ speech_embeds, sources, targets = [], [], []
123
+ for speech_embed, audio_embed, input_id, label in zip(speeches, audios, input_ids, labels):
124
+ speech_embed, audio_embed = speech_embed.to('cuda'), audio_embed.to('cuda')
125
+ # auditory embeds
126
+ speech_embed = self.ln_speech(speech_embed)
127
+ audio_embed = self.ln_audio(audio_embed)
128
+ audio_embed = F.pad(audio_embed, (0, 0, 0, speech_embed.size(1) - audio_embed.size(1)))
129
+ speech_embed = torch.cat([speech_embed, audio_embed], dim=-1)
130
+
131
+ # split frames
132
+ B, T, C = speech_embed.shape
133
+ kernel, stride = round(T * self.second_per_frame / 30.0), round(T * self.second_stride / 30.0)
134
+ kernel, stride = (1, kernel), (1, stride)
135
+ speech_embeds_tr = speech_embed.transpose(1, 2).unsqueeze(2)
136
+ speech_embeds_overlap = F.unfold(speech_embeds_tr, kernel_size=kernel, dilation=1, padding=0, stride=stride)
137
+ _, _, L = speech_embeds_overlap.shape
138
+ speech_embeds_overlap = speech_embeds_overlap.view(B, -1, kernel[1], L)
139
+ speech_embeds_overlap = torch.permute(speech_embeds_overlap, [0, 3, 2, 1])
140
+ speech_embed = speech_embeds_overlap.reshape(-1, kernel[1], C)
141
+ speech_atts = torch.ones(speech_embed.size()[:-1], dtype=torch.long, device=speech_embed.device)
142
+
143
+ # Qformer
144
+ query_tokens = self.speech_query_tokens.expand(speech_embed.shape[0], -1, -1)
145
+ query_output = self.speech_Qformer.bert(
146
+ query_embeds=query_tokens,
147
+ encoder_hidden_states=speech_embed,
148
+ encoder_attention_mask=speech_atts,
149
+ return_dict=True,
150
+ use_cache=False
151
+ )
152
+ speech_embed = self.speech_llama_proj(query_output.last_hidden_state)
153
+ speech_embed = speech_embed.view(B, -1, speech_embed.size(2)).contiguous()
154
+
155
+ sources.append(
156
+ torch.concat([
157
+ torch.LongTensor([self.tokenizer.bos_token_id]).to(input_id[0].device),
158
+ input_id[0],
159
+ torch.LongTensor([self.tokenizer.bos_token_id] * speech_embed.shape[1]).to(input_id[0].device),
160
+ input_id[1],
161
+ torch.LongTensor([self.tokenizer.eos_token_id]).to(input_id[0].device),
162
+ ])
163
+ )
164
+ targets.append(
165
+ torch.concat([
166
+ torch.LongTensor([IGNORE_INDEX]).to(label[0].device),
167
+ label[0],
168
+ torch.LongTensor([IGNORE_INDEX] * speech_embed.shape[1]).to(label[0].device),
169
+ label[1],
170
+ torch.LongTensor([self.tokenizer.eos_token_id]).to(label[0].device),
171
+ ])
172
+ )
173
+ speech_embeds.append(speech_embed)
174
+
175
+ start_length = len(input_ids[0][0]) + 1
176
+
177
+ # USER: <Speech>speech_embeds<Speech> prompt\nASSISTANT:
178
+ PADDING_TOKEN = 0
179
+ embed_tokens = self.llama_model.model.model.embed_tokens if self.lora else self.llama_model.model.embed_tokens
180
+
181
+ input_ids = torch.nn.utils.rnn.pad_sequence(sources, batch_first=True, padding_value=PADDING_TOKEN)
182
+ labels = torch.nn.utils.rnn.pad_sequence(targets, batch_first=True, padding_value=PADDING_TOKEN)
183
+ attention_mask = input_ids.ne(PADDING_TOKEN)
184
+
185
+ inputs_embeds = []
186
+ for input_id, speech_embed in zip(input_ids, speech_embeds):
187
+ left_embeds = embed_tokens(input_id[:start_length])
188
+ right_embeds = embed_tokens(input_id[start_length + speech_embed.shape[1]:])
189
+ concat_tensor = torch.concat([left_embeds, speech_embed[0], right_embeds], dim=0).contiguous()
190
+ inputs_embeds.append(concat_tensor)
191
+
192
+ inputs_embeds = torch.stack(inputs_embeds)
193
+
194
+ return self.llama_model.forward(
195
+ attention_mask=attention_mask,
196
+ position_ids=position_ids,
197
+ past_key_values=past_key_values,
198
+ inputs_embeds=inputs_embeds,
199
+ labels=labels,
200
+ use_cache=False,
201
+ output_attentions=output_attentions,
202
+ output_hidden_states=output_hidden_states,
203
+ return_dict=return_dict
204
+ )
205
+
206
+ def generate(
207
+ self,
208
+ wav_path, prompt, prompt_pattern="USER: <Speech><SpeechHere></Speech> {}\nASSISTANT:", device='cuda:0',
209
+ max_length=2048, num_beams=4, do_sample=True, min_length=1, top_p=0.9, top_k=50,
210
+ repetition_penalty=1.0, length_penalty=1.0, temperature=1.0, bdr=(0, 240), num_return_sequences=1
211
+ ):
212
+ # read wav
213
+ wav, sr = sf.read(wav_path)
214
+ if len(wav.shape) == 2:
215
+ wav = wav[:, 0]
216
+ wav = wav[int(bdr[0] * sr): int(bdr[1] * sr)]
217
+ if sr != 16000:
218
+ wav = librosa.resample(wav, orig_sr=sr, target_sr=16000, res_type="fft")
219
+
220
+ # whisper
221
+ spectrogram = self.feature_extractor(wav, return_tensors="pt", sampling_rate=16000).input_features.to(
222
+ device) # [1, 80, 3000]
223
+ speech_embeds = self.speech_encoder(spectrogram, return_dict=True).last_hidden_state
224
+
225
+ # beats
226
+ raw_wav = torch.from_numpy(wav).to(device).unsqueeze(0)
227
+ audio_padding_mask = torch.zeros(raw_wav.shape, device=device).bool()
228
+ audio_embeds, _ = self.beats.extract_features(raw_wav, padding_mask=audio_padding_mask, feature_only=True)
229
+
230
+ # auditory embeds
231
+ speech_embeds = self.ln_speech(speech_embeds)
232
+ audio_embeds = self.ln_audio(audio_embeds)
233
+ audio_embeds = F.pad(audio_embeds, (0, 0, 0, speech_embeds.size(1) - audio_embeds.size(1)))
234
+ speech_embeds = torch.cat([speech_embeds, audio_embeds], dim=-1)
235
+
236
+ # split frames
237
+ B, T, C = speech_embeds.shape
238
+ kernel, stride = round(T * self.second_per_frame / 30.0), round(T * self.second_stride / 30.0)
239
+ kernel, stride = (1, kernel), (1, stride)
240
+ speech_embeds_tr = speech_embeds.transpose(1, 2).unsqueeze(2)
241
+ speech_embeds_overlap = F.unfold(speech_embeds_tr, kernel_size=kernel, dilation=1, padding=0, stride=stride)
242
+ _, _, L = speech_embeds_overlap.shape
243
+ speech_embeds_overlap = speech_embeds_overlap.view(B, -1, kernel[1], L)
244
+ speech_embeds_overlap = torch.permute(speech_embeds_overlap, [0, 3, 2, 1])
245
+ speech_embeds = speech_embeds_overlap.reshape(-1, kernel[1], C)
246
+ speech_atts = torch.ones(speech_embeds.size()[:-1], dtype=torch.long, device=speech_embeds.device)
247
+
248
+ # Qformer
249
+ query_tokens = self.speech_query_tokens.expand(speech_embeds.shape[0], -1, -1)
250
+ query_output = self.speech_Qformer.bert(
251
+ query_embeds=query_tokens,
252
+ encoder_hidden_states=speech_embeds,
253
+ encoder_attention_mask=speech_atts,
254
+ return_dict=True,
255
+ )
256
+ speech_embeds = self.speech_llama_proj(query_output.last_hidden_state)
257
+ speech_embeds = speech_embeds.view(B, -1, speech_embeds.size(2)).contiguous()
258
+
259
+ # USER: <Speech>speech_embeds<Speech> prompt\nASSISTANT:
260
+ embed_tokens = self.llama_model.model.model.embed_tokens if self.lora else self.llama_model.model.embed_tokens
261
+ prompt_left, prompts_right = prompt_pattern.format(prompt).split('<SpeechHere>')
262
+
263
+ prompt_left_ids = self.tokenizer(prompt_left, return_tensors="pt", add_special_tokens=False).to(
264
+ speech_embeds.device).input_ids
265
+ prompt_left_embeds = embed_tokens(prompt_left_ids)
266
+
267
+ prompt_right_ids = self.tokenizer(prompts_right, return_tensors="pt", add_special_tokens=False).to(
268
+ speech_embeds.device).input_ids
269
+ prompt_right_embeds = embed_tokens(prompt_right_ids)
270
+
271
+ bos_embeds = self.llama_model.model.embed_tokens(
272
+ torch.ones([1, 1], dtype=torch.long, device=device) * self.tokenizer.bos_token_id
273
+ ) if not self.lora else self.llama_model.model.model.embed_tokens(
274
+ torch.ones([1, 1], dtype=torch.long, device=device) * self.tokenizer.bos_token_id
275
+ )
276
+
277
+ embeds = torch.cat([bos_embeds, prompt_left_embeds, speech_embeds, prompt_right_embeds], dim=1)
278
+ atts = torch.ones(embeds.size()[:-1], dtype=torch.long).to(embeds.device)
279
+
280
+ # generate
281
+ output = self.llama_model.generate(
282
+ inputs_embeds=embeds,
283
+ max_length=max_length,
284
+ num_beams=num_beams,
285
+ do_sample=do_sample,
286
+ min_length=min_length,
287
+ top_p=top_p,
288
+ top_k=top_k,
289
+ repetition_penalty=repetition_penalty,
290
+ length_penalty=length_penalty,
291
+ temperature=temperature,
292
+ num_return_sequences=num_return_sequences,
293
+ attention_mask=atts,
294
+ bos_token_id=self.tokenizer.bos_token_id,
295
+ eos_token_id=self.tokenizer.eos_token_id,
296
+ pad_token_id=self.tokenizer.pad_token_id,
297
+ # use_cache=False
298
+ )
299
+
300
+ output_text = self.tokenizer.batch_decode(output, add_special_tokens=False, skip_special_tokens=True)
301
+
302
+ # output_text = self.tokenizer.batch_decode(output)
303
+ return output_text
304
+
305
+ def init_speech_Qformer(self, num_query_token, speech_width, num_hidden_layers=2):
306
+ encoder_config = BertConfig()
307
+ encoder_config.num_hidden_layers = num_hidden_layers
308
+ encoder_config.encoder_width = speech_width
309
+ encoder_config.add_cross_attention = True
310
+ encoder_config.cross_attention_freq = 1
311
+ encoder_config.query_length = num_query_token
312
+ Qformer = BertLMHeadModel(config=encoder_config)
313
+ query_tokens = nn.Parameter(
314
+ torch.zeros(1, num_query_token, encoder_config.hidden_size)
315
+ )
316
+ query_tokens.data.normal_(mean=0.0, std=encoder_config.initializer_range)
317
+ return Qformer, query_tokens
modeling_llama.py ADDED
@@ -0,0 +1,885 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch LLaMA model."""
21
+ import math
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
31
+ from transformers.modeling_utils import PreTrainedModel
32
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
33
+ from transformers.models.llama.configuration_llama import LlamaConfig
34
+
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+ _CONFIG_FOR_DOC = "LlamaConfig"
39
+
40
+
41
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
42
+ def _make_causal_mask(
43
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
44
+ ):
45
+ """
46
+ Make causal mask used for bi-directional self-attention.
47
+ """
48
+ bsz, tgt_len = input_ids_shape
49
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
50
+ mask_cond = torch.arange(mask.size(-1), device=device)
51
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
52
+ mask = mask.to(dtype)
53
+
54
+ if past_key_values_length > 0:
55
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
56
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
57
+
58
+
59
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
60
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
61
+ """
62
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
63
+ """
64
+ bsz, src_len = mask.size()
65
+ tgt_len = tgt_len if tgt_len is not None else src_len
66
+
67
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
68
+
69
+ inverted_mask = 1.0 - expanded_mask
70
+
71
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
72
+
73
+
74
+ class LlamaRMSNorm(nn.Module):
75
+ def __init__(self, hidden_size, eps=1e-6):
76
+ """
77
+ LlamaRMSNorm is equivalent to T5LayerNorm
78
+ """
79
+ super().__init__()
80
+ self.weight = nn.Parameter(torch.ones(hidden_size))
81
+ self.variance_epsilon = eps
82
+
83
+ def forward(self, hidden_states):
84
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
85
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
86
+
87
+ # convert into half-precision if necessary
88
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
89
+ hidden_states = hidden_states.to(self.weight.dtype)
90
+
91
+ return self.weight * hidden_states
92
+
93
+
94
+ class LlamaRotaryEmbedding(torch.nn.Module):
95
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
96
+ super().__init__()
97
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
98
+ self.register_buffer("inv_freq", inv_freq)
99
+
100
+ # Build here to make `torch.jit.trace` work.
101
+ self.max_seq_len_cached = max_position_embeddings
102
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
103
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
104
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
105
+ emb = torch.cat((freqs, freqs), dim=-1)
106
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
107
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
108
+
109
+ def forward(self, x, seq_len=None):
110
+ # x: [bs, num_attention_heads, seq_len, head_size]
111
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
112
+ if seq_len > self.max_seq_len_cached:
113
+ self.max_seq_len_cached = seq_len
114
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
115
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
116
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
117
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
118
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
119
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
120
+ return (
121
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
122
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
123
+ )
124
+
125
+
126
+ def rotate_half(x):
127
+ """Rotates half the hidden dims of the input."""
128
+ x1 = x[..., : x.shape[-1] // 2]
129
+ x2 = x[..., x.shape[-1] // 2 :]
130
+ return torch.cat((-x2, x1), dim=-1)
131
+
132
+
133
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
134
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
135
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
136
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
137
+ cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
138
+ sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
139
+ q_embed = (q * cos) + (rotate_half(q) * sin)
140
+ k_embed = (k * cos) + (rotate_half(k) * sin)
141
+ return q_embed, k_embed
142
+
143
+
144
+ class LlamaMLP(nn.Module):
145
+ def __init__(
146
+ self,
147
+ hidden_size: int,
148
+ intermediate_size: int,
149
+ hidden_act: str,
150
+ ):
151
+ super().__init__()
152
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
153
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
154
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
155
+ self.act_fn = ACT2FN[hidden_act]
156
+
157
+ def forward(self, x):
158
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
159
+
160
+
161
+ class LlamaAttention(nn.Module):
162
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
163
+
164
+ def __init__(self, config: LlamaConfig):
165
+ super().__init__()
166
+ self.config = config
167
+ self.hidden_size = config.hidden_size
168
+ self.num_heads = config.num_attention_heads
169
+ self.head_dim = self.hidden_size // self.num_heads
170
+ self.max_position_embeddings = config.max_position_embeddings
171
+
172
+ if (self.head_dim * self.num_heads) != self.hidden_size:
173
+ raise ValueError(
174
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
175
+ f" and `num_heads`: {self.num_heads})."
176
+ )
177
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
178
+ self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
179
+ self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
180
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
181
+ self.rotary_emb = LlamaRotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
182
+
183
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
184
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
185
+
186
+ def forward(
187
+ self,
188
+ hidden_states: torch.Tensor,
189
+ attention_mask: Optional[torch.Tensor] = None,
190
+ position_ids: Optional[torch.LongTensor] = None,
191
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
192
+ output_attentions: bool = False,
193
+ use_cache: bool = False,
194
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
195
+ bsz, q_len, _ = hidden_states.size()
196
+
197
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
198
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
199
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
200
+
201
+ kv_seq_len = key_states.shape[-2]
202
+ if past_key_value is not None:
203
+ kv_seq_len += past_key_value[0].shape[-2]
204
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
205
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
206
+ # [bsz, nh, t, hd]
207
+
208
+ if past_key_value is not None:
209
+ # reuse k, v, self_attention
210
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
211
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
212
+
213
+ past_key_value = (key_states, value_states) if use_cache else None
214
+
215
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
216
+
217
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
218
+ raise ValueError(
219
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
220
+ f" {attn_weights.size()}"
221
+ )
222
+
223
+ if attention_mask is not None:
224
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
225
+ raise ValueError(
226
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
227
+ )
228
+ attn_weights = attn_weights + attention_mask
229
+ attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
230
+
231
+ # upcast attention to fp32
232
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
233
+ attn_output = torch.matmul(attn_weights, value_states)
234
+
235
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
236
+ raise ValueError(
237
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
238
+ f" {attn_output.size()}"
239
+ )
240
+
241
+ attn_output = attn_output.transpose(1, 2)
242
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
243
+
244
+ attn_output = self.o_proj(attn_output)
245
+
246
+ if not output_attentions:
247
+ attn_weights = None
248
+
249
+ return attn_output, attn_weights, past_key_value
250
+
251
+
252
+ class LlamaDecoderLayer(nn.Module):
253
+ def __init__(self, config: LlamaConfig):
254
+ super().__init__()
255
+ self.hidden_size = config.hidden_size
256
+ self.self_attn = LlamaAttention(config=config)
257
+ self.mlp = LlamaMLP(
258
+ hidden_size=self.hidden_size,
259
+ intermediate_size=config.intermediate_size,
260
+ hidden_act=config.hidden_act,
261
+ )
262
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
263
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
264
+
265
+ def forward(
266
+ self,
267
+ hidden_states: torch.Tensor,
268
+ attention_mask: Optional[torch.Tensor] = None,
269
+ position_ids: Optional[torch.LongTensor] = None,
270
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
271
+ output_attentions: Optional[bool] = False,
272
+ use_cache: Optional[bool] = False,
273
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
274
+ """
275
+ Args:
276
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
277
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
278
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
279
+ output_attentions (`bool`, *optional*):
280
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
281
+ returned tensors for more detail.
282
+ use_cache (`bool`, *optional*):
283
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
284
+ (see `past_key_values`).
285
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
286
+ """
287
+
288
+ residual = hidden_states
289
+
290
+ hidden_states = self.input_layernorm(hidden_states)
291
+
292
+ # Self Attention
293
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
294
+ hidden_states=hidden_states,
295
+ attention_mask=attention_mask,
296
+ position_ids=position_ids,
297
+ past_key_value=past_key_value,
298
+ output_attentions=output_attentions,
299
+ use_cache=use_cache,
300
+ )
301
+ hidden_states = residual + hidden_states
302
+
303
+ # Fully Connected
304
+ residual = hidden_states
305
+ hidden_states = self.post_attention_layernorm(hidden_states)
306
+ hidden_states = self.mlp(hidden_states)
307
+ hidden_states = residual + hidden_states
308
+
309
+ outputs = (hidden_states,)
310
+
311
+ if output_attentions:
312
+ outputs += (self_attn_weights,)
313
+
314
+ if use_cache:
315
+ outputs += (present_key_value,)
316
+
317
+ return outputs
318
+
319
+
320
+ LLAMA_START_DOCSTRING = r"""
321
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
322
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
323
+ etc.)
324
+
325
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
326
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
327
+ and behavior.
328
+
329
+ Parameters:
330
+ config ([`LlamaConfig`]):
331
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
332
+ load the weights associated with the model, only the configuration. Check out the
333
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
334
+ """
335
+
336
+
337
+ @add_start_docstrings(
338
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
339
+ LLAMA_START_DOCSTRING,
340
+ )
341
+ class LlamaPreTrainedModel(PreTrainedModel):
342
+ config_class = LlamaConfig
343
+ base_model_prefix = "model"
344
+ supports_gradient_checkpointing = True
345
+ _no_split_modules = ["LlamaDecoderLayer"]
346
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
347
+
348
+ def _init_weights(self, module):
349
+ std = self.config.initializer_range
350
+ if isinstance(module, nn.Linear):
351
+ module.weight.data.normal_(mean=0.0, std=std)
352
+ if module.bias is not None:
353
+ module.bias.data.zero_()
354
+ elif isinstance(module, nn.Embedding):
355
+ module.weight.data.normal_(mean=0.0, std=std)
356
+ if module.padding_idx is not None:
357
+ module.weight.data[module.padding_idx].zero_()
358
+
359
+ def _set_gradient_checkpointing(self, module, value=False):
360
+ if isinstance(module, LlamaModel):
361
+ module.gradient_checkpointing = value
362
+
363
+
364
+ LLAMA_INPUTS_DOCSTRING = r"""
365
+ Args:
366
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
367
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
368
+ it.
369
+
370
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
371
+ [`PreTrainedTokenizer.__call__`] for details.
372
+
373
+ [What are input IDs?](../glossary#input-ids)
374
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
375
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
376
+
377
+ - 1 for tokens that are **not masked**,
378
+ - 0 for tokens that are **masked**.
379
+
380
+ [What are attention masks?](../glossary#attention-mask)
381
+
382
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
383
+ [`PreTrainedTokenizer.__call__`] for details.
384
+
385
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
386
+ `past_key_values`).
387
+
388
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
389
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
390
+ information on the default strategy.
391
+
392
+ - 1 indicates the head is **not masked**,
393
+ - 0 indicates the head is **masked**.
394
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
395
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
396
+ config.n_positions - 1]`.
397
+
398
+ [What are position IDs?](../glossary#position-ids)
399
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
400
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
401
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
402
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
403
+
404
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
405
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
406
+
407
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
408
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
409
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
410
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
411
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
412
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
413
+ model's internal embedding lookup matrix.
414
+ use_cache (`bool`, *optional*):
415
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
416
+ `past_key_values`).
417
+ output_attentions (`bool`, *optional*):
418
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
419
+ tensors for more detail.
420
+ output_hidden_states (`bool`, *optional*):
421
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
422
+ more detail.
423
+ return_dict (`bool`, *optional*):
424
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
425
+ """
426
+
427
+
428
+ @add_start_docstrings(
429
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
430
+ LLAMA_START_DOCSTRING,
431
+ )
432
+ class LlamaModel(LlamaPreTrainedModel):
433
+ """
434
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
435
+
436
+ Args:
437
+ config: LlamaConfig
438
+ """
439
+
440
+ def __init__(self, config: LlamaConfig):
441
+ super().__init__(config)
442
+ self.padding_idx = config.pad_token_id
443
+ self.vocab_size = config.vocab_size
444
+
445
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
446
+ self.layers = nn.ModuleList([LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)])
447
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
448
+
449
+ self.gradient_checkpointing = False
450
+ # Initialize weights and apply final processing
451
+ self.post_init()
452
+
453
+ def get_input_embeddings(self):
454
+ return self.embed_tokens
455
+
456
+ def set_input_embeddings(self, value):
457
+ self.embed_tokens = value
458
+
459
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
460
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
461
+ # create causal mask
462
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
463
+ combined_attention_mask = None
464
+ if input_shape[-1] > 1:
465
+ combined_attention_mask = _make_causal_mask(
466
+ input_shape,
467
+ inputs_embeds.dtype,
468
+ device=inputs_embeds.device,
469
+ past_key_values_length=past_key_values_length,
470
+ )
471
+
472
+ if attention_mask is not None:
473
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
474
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
475
+ inputs_embeds.device
476
+ )
477
+ combined_attention_mask = (
478
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
479
+ )
480
+
481
+ return combined_attention_mask
482
+
483
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
484
+ def forward(
485
+ self,
486
+ input_ids: torch.LongTensor = None,
487
+ attention_mask: Optional[torch.Tensor] = None,
488
+ position_ids: Optional[torch.LongTensor] = None,
489
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
490
+ inputs_embeds: Optional[torch.FloatTensor] = None,
491
+ use_cache: Optional[bool] = None,
492
+ output_attentions: Optional[bool] = None,
493
+ output_hidden_states: Optional[bool] = None,
494
+ return_dict: Optional[bool] = None,
495
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
496
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
497
+ output_hidden_states = (
498
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
499
+ )
500
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
501
+
502
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
503
+
504
+ # retrieve input_ids and inputs_embeds
505
+ if input_ids is not None and inputs_embeds is not None:
506
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
507
+ elif input_ids is not None:
508
+ batch_size, seq_length = input_ids.shape
509
+ elif inputs_embeds is not None:
510
+ batch_size, seq_length, _ = inputs_embeds.shape
511
+ else:
512
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
513
+
514
+ seq_length_with_past = seq_length
515
+ past_key_values_length = 0
516
+
517
+ if past_key_values is not None:
518
+ past_key_values_length = past_key_values[0][0].shape[2]
519
+ seq_length_with_past = seq_length_with_past + past_key_values_length
520
+
521
+ if position_ids is None:
522
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
523
+ position_ids = torch.arange(
524
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
525
+ )
526
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
527
+ else:
528
+ position_ids = position_ids.view(-1, seq_length).long()
529
+
530
+ if inputs_embeds is None:
531
+ inputs_embeds = self.embed_tokens(input_ids)
532
+ # embed positions
533
+ if attention_mask is None:
534
+ attention_mask = torch.ones(
535
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
536
+ )
537
+ attention_mask = self._prepare_decoder_attention_mask(
538
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
539
+ )
540
+
541
+ hidden_states = inputs_embeds
542
+
543
+ if self.gradient_checkpointing and self.training:
544
+ if use_cache:
545
+ logger.warning_once(
546
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
547
+ )
548
+ use_cache = False
549
+
550
+ # decoder layers
551
+ all_hidden_states = () if output_hidden_states else None
552
+ all_self_attns = () if output_attentions else None
553
+ next_decoder_cache = () if use_cache else None
554
+
555
+ for idx, decoder_layer in enumerate(self.layers):
556
+ if output_hidden_states:
557
+ all_hidden_states += (hidden_states,)
558
+
559
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
560
+
561
+ if self.gradient_checkpointing and self.training:
562
+
563
+ def create_custom_forward(module):
564
+ def custom_forward(*inputs):
565
+ # None for past_key_value
566
+ return module(*inputs, output_attentions, None)
567
+
568
+ return custom_forward
569
+
570
+ layer_outputs = torch.utils.checkpoint.checkpoint(
571
+ create_custom_forward(decoder_layer),
572
+ hidden_states,
573
+ attention_mask,
574
+ position_ids,
575
+ None,
576
+ )
577
+ else:
578
+ layer_outputs = decoder_layer(
579
+ hidden_states,
580
+ attention_mask=attention_mask,
581
+ position_ids=position_ids,
582
+ past_key_value=past_key_value,
583
+ output_attentions=output_attentions,
584
+ use_cache=use_cache,
585
+ )
586
+
587
+ hidden_states = layer_outputs[0]
588
+
589
+ if use_cache:
590
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
591
+
592
+ if output_attentions:
593
+ all_self_attns += (layer_outputs[1],)
594
+
595
+ hidden_states = self.norm(hidden_states)
596
+
597
+ # add hidden states from the last decoder layer
598
+ if output_hidden_states:
599
+ all_hidden_states += (hidden_states,)
600
+
601
+ next_cache = next_decoder_cache if use_cache else None
602
+ if not return_dict:
603
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
604
+ return BaseModelOutputWithPast(
605
+ last_hidden_state=hidden_states,
606
+ past_key_values=next_cache,
607
+ hidden_states=all_hidden_states,
608
+ attentions=all_self_attns,
609
+ )
610
+
611
+
612
+ class LlamaForCausalLM(LlamaPreTrainedModel):
613
+ def __init__(self, config):
614
+ super().__init__(config)
615
+ self.model = LlamaModel(config)
616
+
617
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
618
+
619
+ # Initialize weights and apply final processing
620
+ self.post_init()
621
+
622
+ def get_input_embeddings(self):
623
+ return self.model.embed_tokens
624
+
625
+ def set_input_embeddings(self, value):
626
+ self.model.embed_tokens = value
627
+
628
+ def get_output_embeddings(self):
629
+ return self.lm_head
630
+
631
+ def set_output_embeddings(self, new_embeddings):
632
+ self.lm_head = new_embeddings
633
+
634
+ def set_decoder(self, decoder):
635
+ self.model = decoder
636
+
637
+ def get_decoder(self):
638
+ return self.model
639
+
640
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
641
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
642
+ def forward(
643
+ self,
644
+ input_ids: torch.LongTensor = None,
645
+ attention_mask: Optional[torch.Tensor] = None,
646
+ position_ids: Optional[torch.LongTensor] = None,
647
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
648
+ inputs_embeds: Optional[torch.FloatTensor] = None,
649
+ labels: Optional[torch.LongTensor] = None,
650
+ use_cache: Optional[bool] = None,
651
+ output_attentions: Optional[bool] = None,
652
+ output_hidden_states: Optional[bool] = None,
653
+ return_dict: Optional[bool] = None,
654
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
655
+ r"""
656
+ Args:
657
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
658
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
659
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
660
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
661
+
662
+ Returns:
663
+
664
+ Example:
665
+
666
+ ```python
667
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
668
+
669
+ >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
670
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
671
+
672
+ >>> prompt = "Hey, are you consciours? Can you talk to me?"
673
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
674
+
675
+ >>> # Generate
676
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
677
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
678
+ "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
679
+ ```"""
680
+
681
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
682
+ output_hidden_states = (
683
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
684
+ )
685
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
686
+
687
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
688
+ outputs = self.model(
689
+ input_ids=input_ids,
690
+ attention_mask=attention_mask,
691
+ position_ids=position_ids,
692
+ past_key_values=past_key_values,
693
+ inputs_embeds=inputs_embeds,
694
+ use_cache=use_cache,
695
+ output_attentions=output_attentions,
696
+ output_hidden_states=output_hidden_states,
697
+ return_dict=return_dict,
698
+ )
699
+
700
+ hidden_states = outputs[0]
701
+ logits = self.lm_head(hidden_states)
702
+
703
+ loss = None
704
+ if labels is not None:
705
+ # Shift so that tokens < n predict n
706
+ shift_logits = logits[..., :-1, :].contiguous()
707
+ shift_labels = labels[..., 1:].contiguous()
708
+ # Flatten the tokens
709
+ loss_fct = CrossEntropyLoss()
710
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
711
+ shift_labels = shift_labels.view(-1)
712
+ # Enable model parallelism
713
+ shift_labels = shift_labels.to(shift_logits.device)
714
+ loss = loss_fct(shift_logits, shift_labels)
715
+
716
+ if not return_dict:
717
+ output = (logits,) + outputs[1:]
718
+ return (loss,) + output if loss is not None else output
719
+
720
+ return CausalLMOutputWithPast(
721
+ loss=loss,
722
+ logits=logits,
723
+ past_key_values=outputs.past_key_values,
724
+ hidden_states=outputs.hidden_states,
725
+ attentions=outputs.attentions,
726
+ )
727
+
728
+ def prepare_inputs_for_generation(
729
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
730
+ ):
731
+ if past_key_values:
732
+ input_ids = input_ids[:, -1:]
733
+
734
+ position_ids = kwargs.get("position_ids", None)
735
+ if attention_mask is not None and position_ids is None:
736
+ # create position_ids on the fly for batch generation
737
+ position_ids = attention_mask.long().cumsum(-1) - 1
738
+ position_ids.masked_fill_(attention_mask == 0, 1)
739
+ if past_key_values:
740
+ position_ids = position_ids[:, -1].unsqueeze(-1)
741
+
742
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
743
+ if inputs_embeds is not None and past_key_values is None:
744
+ model_inputs = {"inputs_embeds": inputs_embeds}
745
+ else:
746
+ model_inputs = {"input_ids": input_ids}
747
+
748
+ model_inputs.update(
749
+ {
750
+ "position_ids": position_ids,
751
+ "past_key_values": past_key_values,
752
+ "use_cache": kwargs.get("use_cache"),
753
+ "attention_mask": attention_mask,
754
+ }
755
+ )
756
+ return model_inputs
757
+
758
+ @staticmethod
759
+ def _reorder_cache(past_key_values, beam_idx):
760
+ reordered_past = ()
761
+ for layer_past in past_key_values:
762
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
763
+ return reordered_past
764
+
765
+
766
+ @add_start_docstrings(
767
+ """
768
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
769
+
770
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
771
+ (e.g. GPT-2) do.
772
+
773
+ Since it does classification on the last token, it requires to know the position of the last token. If a
774
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
775
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
776
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
777
+ each row of the batch).
778
+ """,
779
+ LLAMA_START_DOCSTRING,
780
+ )
781
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
782
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
783
+
784
+ def __init__(self, config):
785
+ super().__init__(config)
786
+ self.num_labels = config.num_labels
787
+ self.model = LlamaModel(config)
788
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
789
+
790
+ # Initialize weights and apply final processing
791
+ self.post_init()
792
+
793
+ def get_input_embeddings(self):
794
+ return self.model.embed_tokens
795
+
796
+ def set_input_embeddings(self, value):
797
+ self.model.embed_tokens = value
798
+
799
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
800
+ def forward(
801
+ self,
802
+ input_ids: torch.LongTensor = None,
803
+ attention_mask: Optional[torch.Tensor] = None,
804
+ position_ids: Optional[torch.LongTensor] = None,
805
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
806
+ inputs_embeds: Optional[torch.FloatTensor] = None,
807
+ labels: Optional[torch.LongTensor] = None,
808
+ use_cache: Optional[bool] = None,
809
+ output_attentions: Optional[bool] = None,
810
+ output_hidden_states: Optional[bool] = None,
811
+ return_dict: Optional[bool] = None,
812
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
813
+ r"""
814
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
815
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
816
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
817
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
818
+ """
819
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
820
+
821
+ transformer_outputs = self.model(
822
+ input_ids,
823
+ attention_mask=attention_mask,
824
+ position_ids=position_ids,
825
+ past_key_values=past_key_values,
826
+ inputs_embeds=inputs_embeds,
827
+ use_cache=use_cache,
828
+ output_attentions=output_attentions,
829
+ output_hidden_states=output_hidden_states,
830
+ return_dict=return_dict,
831
+ )
832
+ hidden_states = transformer_outputs[0]
833
+ logits = self.score(hidden_states)
834
+
835
+ if input_ids is not None:
836
+ batch_size = input_ids.shape[0]
837
+ else:
838
+ batch_size = inputs_embeds.shape[0]
839
+
840
+ if self.config.pad_token_id is None and batch_size != 1:
841
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
842
+ if self.config.pad_token_id is None:
843
+ sequence_lengths = -1
844
+ else:
845
+ if input_ids is not None:
846
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
847
+ else:
848
+ sequence_lengths = -1
849
+
850
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
851
+
852
+ loss = None
853
+ if labels is not None:
854
+ labels = labels.to(logits.device)
855
+ if self.config.problem_type is None:
856
+ if self.num_labels == 1:
857
+ self.config.problem_type = "regression"
858
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
859
+ self.config.problem_type = "single_label_classification"
860
+ else:
861
+ self.config.problem_type = "multi_label_classification"
862
+
863
+ if self.config.problem_type == "regression":
864
+ loss_fct = MSELoss()
865
+ if self.num_labels == 1:
866
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
867
+ else:
868
+ loss = loss_fct(pooled_logits, labels)
869
+ elif self.config.problem_type == "single_label_classification":
870
+ loss_fct = CrossEntropyLoss()
871
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
872
+ elif self.config.problem_type == "multi_label_classification":
873
+ loss_fct = BCEWithLogitsLoss()
874
+ loss = loss_fct(pooled_logits, labels)
875
+ if not return_dict:
876
+ output = (pooled_logits,) + transformer_outputs[1:]
877
+ return ((loss,) + output) if loss is not None else output
878
+
879
+ return SequenceClassifierOutputWithPast(
880
+ loss=loss,
881
+ logits=pooled_logits,
882
+ past_key_values=transformer_outputs.past_key_values,
883
+ hidden_states=transformer_outputs.hidden_states,
884
+ attentions=transformer_outputs.attentions,
885
+ )
salmonn_trainer.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+
4
+ from transformers import Trainer
5
+ from typing import Optional
6
+
7
+ LOG_INTERVAL = 5000
8
+
9
+ def get_state(model):
10
+ trainable_state_dict = dict()
11
+ for name, param in model.state_dict().items():
12
+ try:
13
+ if model.get_parameter(name).requires_grad:
14
+ trainable_state_dict[name] = param
15
+ except:
16
+ trainable_state_dict[name] = param
17
+ return trainable_state_dict
18
+
19
+
20
+ class SALMONNTrainer(Trainer):
21
+
22
+ def _save_checkpoint(self, model, trial, metrics=None):
23
+ from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR
24
+ checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{(self.state.global_step // LOG_INTERVAL) * LOG_INTERVAL}"
25
+
26
+ run_dir = self._get_output_dir(trial=trial)
27
+ output_dir = os.path.join(run_dir, checkpoint_folder)
28
+ os.makedirs(output_dir, exist_ok=True)
29
+
30
+ # Only save Adapter
31
+ weight_to_save = get_state(self.model)
32
+ torch.save(weight_to_save, os.path.join(output_dir, f'salomnn_7b.bin'))
33
+
34
+ def _save(self, output_dir: Optional[str] = None, state_dict=None):
35
+ super(SALMONNTrainer, self)._save(output_dir, state_dict)
train.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fp16": {
3
+ "enabled": "auto",
4
+ "loss_scale": 0,
5
+ "loss_scale_window": 1000,
6
+ "initial_scale_power": 16,
7
+ "hysteresis": 2,
8
+ "min_loss_scale": 1
9
+ },
10
+ "bf16": {
11
+ "enabled": "auto"
12
+ },
13
+ "train_micro_batch_size_per_gpu": "auto",
14
+ "train_batch_size": "auto",
15
+ "gradient_accumulation_steps": "auto",
16
+ "zero_optimization": {
17
+ "stage": 2,
18
+ "overlap_comm": true,
19
+ "contiguous_gradients": true,
20
+ "sub_group_size": 1e9,
21
+ "reduce_bucket_size": "auto"
22
+ },
23
+ "wandb": {
24
+ "enabled": true,
25
+ "project": "SALMONN"
26
+ }
27
+ }
train_mem.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright:
2
+ # Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright:
3
+ # Make it more memory efficient by monkey patching the LLaMA model with FlashAttn.
4
+
5
+ # Need to call this before importing transformers.
6
+
7
+ from llama_flash_attn_monkey_patch import replace_llama_attn_with_flash_attn
8
+
9
+ replace_llama_attn_with_flash_attn()
10
+
11
+ from trainer import train
12
+
13
+ if __name__ == "__main__":
14
+ train()
trainer.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright:
2
+ # Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright:
3
+ # Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import os
18
+ from dataclasses import dataclass, field
19
+ import logging
20
+ import pathlib
21
+ from typing import Dict, Optional, Sequence, List
22
+ import torch
23
+ import transformers
24
+ import sys
25
+
26
+ from salmonn_trainer import SALMONNTrainer, get_state
27
+ from dataset import make_supervised_data_module, DataArguments
28
+ from model import SALMONN
29
+ from utils import print_trainable_parameters
30
+
31
+ import wandb
32
+
33
+
34
+ @dataclass
35
+ class ModelArguments:
36
+ ckpt_path: Optional[str] = field(default='./salmonn_7b_v0.pth')
37
+ whisper_path: Optional[str] = field(default='./whisper-large-v2')
38
+ beats_path: Optional[str] = field(default='./BEATs_iter3_plus_AS2M_finetuned_on_AS2M_cpt2.pt')
39
+ vicuna_path: Optional[str] = field(default='./vicuna-7b-v1.5')
40
+ version: Optional[str] = field(default="v0")
41
+ device: Optional[str] = field(default='cuda')
42
+
43
+
44
+ @dataclass
45
+ class TrainingArguments(transformers.TrainingArguments):
46
+ output_dir: Optional[str] = field(default='./checkpoints/')
47
+ optim: str = field(default="adamw_torch")
48
+ bf16: bool = True
49
+ fp16: bool = False
50
+ lora_alpha: int = 32
51
+ model_max_length: int = 2048
52
+ use_cache: bool = False
53
+ gradient_checkpointing: bool = False
54
+
55
+
56
+ def train():
57
+ parser = transformers.HfArgumentParser((ModelArguments, DataArguments, TrainingArguments))
58
+ model_args, data_args, training_args = parser.parse_args_into_dataclasses()
59
+ compute_dtype = (torch.float16 if training_args.fp16 else (torch.bfloat16 if training_args.bf16 else torch.float32))
60
+ wandb.init(project='SALMONN', name=training_args.run_name)
61
+
62
+ model = SALMONN(
63
+ model_args.ckpt_path, model_args.whisper_path, model_args.beats_path, model_args.vicuna_path,
64
+ lora_alpha=training_args.lora_alpha, compute_dtype=compute_dtype
65
+ ).cuda()
66
+ print_trainable_parameters(model, vb=0)
67
+
68
+ data_module = make_supervised_data_module(tokenizer=model.tokenizer, data_args=data_args)
69
+ trainer = SALMONNTrainer(model=model, tokenizer=model.tokenizer, args=training_args, **data_module)
70
+
71
+ trainer.train()
72
+
73
+ # Only save Adapter
74
+ weight_to_save = get_state(model.named_parameters())
75
+ torch.save(weight_to_save, os.path.join(training_args.output_dir, f'salomnn_7b.bin'))
76
+
77
+ trainer.save_state()
78
+
79
+
80
+ if __name__ == "__main__":
81
+ train()
utils.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def print_trainable_parameters(model, vb=0):
2
+ trainable_params = 0
3
+ all_param = 0
4
+ for _, param in model.named_parameters():
5
+ all_param += param.numel()
6
+ if param.requires_grad:
7
+ trainable_params += param.numel()
8
+ if vb > 0:
9
+ print(_, param.requires_grad, param.numel())
10
+ print(
11
+ f"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param:.2f}"
12
+ )