-
Notifications
You must be signed in to change notification settings - Fork 212
/
template.py
2117 lines (1810 loc) · 91.8 KB
/
template.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) Alibaba, Inc. and its affiliates.
import re
from copy import deepcopy
from io import BytesIO
from typing import Any, Dict, List, Literal, Optional, Tuple, Union
import json
import requests
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.nn.utils.rnn import pad_sequence
from transformers import PreTrainedTokenizerBase, StoppingCriteria
from swift.llm.agent.utils import calculate_loss_scale, get_tools_prompt
from swift.torchacc_utils import pad_and_split_batch
from swift.utils import get_dist_setting, upper_bound, use_torchacc
DEFAULT_SYSTEM = 'You are a helpful assistant.'
History = List[Union[Tuple[str, str], List[str]]]
Prompt = List[Union[str, List[int], List[str]]]
StopWords = Prompt
Context = Union[str, List[int]]
TEMPLATE_MAPPING: Dict[str, Dict[str, Any]] = {}
class TemplateType:
# text-generation
default_generation = 'default-generation'
chatglm_generation = 'chatglm-generation'
qwen_audio_generation = 'qwen-audio-generation'
# chat
default = 'default'
qwen = 'qwen'
qwen_vl = 'qwen-vl'
qwen_audio = 'qwen-audio'
modelscope_agent = 'modelscope-agent'
baichuan = 'baichuan'
chatglm2 = 'chatglm2'
chatglm3 = 'chatglm3'
llama = 'llama' # llama2
llama3 = 'llama3'
llava1_5 = 'llava1_5'
llava_mistral = 'llava-mistral'
llava_vicuna = 'llava-vicuna'
llava_yi = 'llava-yi'
llava_llama_instruct = 'llava-llama-instruct'
llava_qwen_instruct = 'llava-qwen-instruct'
llama_llava_next = 'llama-llava-next'
openbuddy = 'openbuddy'
openbuddy2 = 'openbuddy2'
internlm = 'internlm'
internlm2 = 'internlm2'
internlm_xcomposer2 = 'internlm-xcomposer2'
internvl = 'internvl'
internvl_phi3 = 'internvl-phi3'
florence = 'florence'
yi = 'yi'
yi1_5 = 'yi1_5'
yi_vl = 'yi-vl'
yuan = 'yuan'
xverse = 'xverse'
ziya = 'ziya'
skywork = 'skywork'
bluelm = 'bluelm'
zephyr = 'zephyr'
sus = 'sus'
deepseek = 'deepseek'
deepseek_coder = 'deepseek-coder'
deepseek_vl = 'deepseek-vl'
deepseek2 = 'deepseek2'
codefuse_codellama = 'codefuse-codellama'
codefuse = 'codefuse'
cogvlm = 'cogvlm'
glm4v = 'glm4v'
cogagent_chat = 'cogagent-chat'
cogagent_instruct = 'cogagent-instruct'
orion = 'orion'
minicpm = 'minicpm'
minicpm_v = 'minicpm-v'
minicpm_v_v2_5 = 'minicpm-v-v2_5'
gemma = 'gemma'
paligemma = 'paligemma'
mplug_owl2 = 'mplug-owl2'
wizardlm2_awq = 'wizardlm2-awq'
wizardlm2 = 'wizardlm2'
atom = 'atom'
phi3 = 'phi3'
phi3_vl = 'phi3-vl'
telechat = 'telechat'
telechat_v2 = 'telechat-v2'
dbrx = 'dbrx'
mengzi = 'mengzi'
c4ai = 'c4ai'
chatml = 'chatml'
# compatibility. (Deprecated)
default_generation_bos = 'default-generation-bos'
@classmethod
def get_template_name_list(cls) -> List[str]:
res = []
for k in cls.__dict__.keys():
if k.startswith('__') or k == 'get_template_name_list':
continue
res.append(cls.__dict__[k])
return res
class StopWordsCriteria(StoppingCriteria):
# The returned sentence includes stop words.
def __init__(self, tokenizer: PreTrainedTokenizerBase, stop_words: StopWords, **tokenizer_kwargs) -> None:
self.tokenizer = tokenizer
self.stop_words = stop_words
self.tokenizer_kwargs = tokenizer_kwargs
self.start_idx = -1
def __call__(self, input_ids: Tensor, scores: Tensor, **kwargs) -> bool:
if self.start_idx == -1:
self.start_idx = len(input_ids[0]) - 1
tokenizer = self.tokenizer
stop_words = self.stop_words
# [-20:]: Assuming the end tokens do not exceed 20 tokens,
# to avoid input_ids being too long and affecting efficiency.
text = tokenizer.decode(input_ids[0, self.start_idx:][-20:], **self.tokenizer_kwargs)
for stop_word in stop_words:
if isinstance(stop_word, str):
if stop_word in text:
return True
else: # list
if len(stop_word) > 0 and input_ids[0].tolist()[-len(stop_word):] == stop_word:
return True
return False
class Template:
"""A template class for all supported models.
Args:
prefix: Prefix tokens before the first turn's prompt
prompt: A list of elements whose types are str and list of integers. The input query part of every turn.
chat_sep: The chat separators between every turn.
suffix: The end tokens after the chat finished.
default_system: A default system instruction.
system_prefix: The prefix if the `system` is not empty.
auto_add_bos: By default, the bos_token is not added. The auto_add_bos option will determine
whether to add it based on `tokenizer.encode('')`.
Examples:
<start>system\nYou are a helpful assistant!<end>\n<bos><start>Who are you?<end>\n<start>assistant:I am a robot<end>\n<start>Who are you?<end>\n<start>assistant:I am a robot<end> # noqa
--------------- -------------------------- --- ----- ------------ ----------------------- ----------- ---- -----
system_prefix system prefix prompt query prompt response chat_sep suffix
"""
special_tokens = ['<image>', '<video_label>', '<audio_label>', '<bbox>', '<ref-object>']
special_keys = ['images', 'videos', 'audios', 'objects']
def __init__(self,
prefix: Prompt,
prompt: Prompt,
chat_sep: Optional[Prompt],
suffix: Prompt,
default_system: Optional[str] = None,
system_prefix: Optional[Prompt] = None,
auto_add_bos: bool = False,
tools_prompt: str = 'react_en',
tool_prompt: Optional[Prompt] = None) -> None:
# check
for x in [prefix, prompt, chat_sep, suffix, system_prefix]:
assert x is None or isinstance(x, list)
if default_system == '':
default_system = None
if self._has_system(prefix):
assert system_prefix is None, 'The prefix already contains {{SYSTEM}}.'
system_prefix = prefix
prefix = self._replace_system(prefix)
self.prefix = prefix
self.system_prefix = system_prefix
if self.system_prefix is None:
assert default_system is None, 'The template does not support `system`.'
self.prompt = prompt
self.chat_sep = chat_sep
self.support_multi_round = self.chat_sep is not None
self.suffix = suffix
self.default_system = default_system
self.use_default_system = True
self.auto_add_bos = auto_add_bos
self._is_init = False
self.tools_prompt = tools_prompt
self.tool_prompt = tool_prompt if tool_prompt is not None else self.prompt # default as user
@staticmethod
def _replace_system(prefix: Prompt) -> Prompt:
return [p.replace('{{SYSTEM}}', '') for p in prefix if '{{SYSTEM}}' in p]
@staticmethod
def _has_system(prefix: Prompt) -> bool:
return any(['{{SYSTEM}}' in p for p in prefix])
@staticmethod
def _preprocess_prompt(tokenizer: PreTrainedTokenizerBase, value: Optional[Prompt]) -> Optional[Prompt]:
"""Turn `eos_token_id` to token id
e.g. [['eos_token_id']] -> [[2]]
"""
if value is None:
return None
res_value = []
for v in value:
if isinstance(v, list):
res_v = []
for sub_v in v:
if isinstance(sub_v, str):
sub_v = getattr(tokenizer, sub_v)
res_v.append(sub_v)
v = res_v
res_value.append(v)
return res_value
def _init_template(self,
tokenizer: PreTrainedTokenizerBase,
default_system: Optional[str] = None,
max_length: Optional[int] = None,
truncation_strategy: Literal['delete', 'truncation_left'] = 'delete',
**kwargs) -> None:
assert self._is_init is False, 'The template has been initialized.'
self._is_init = True
self.tokenizer = tokenizer
# if default_system is None. not change self.default_system
if default_system == '':
self.default_system = None
elif default_system is not None:
assert self.system_prefix is not None, (
f'The template does not support `system`, template_type: {getattr(self, "template_type", None)}')
self.default_system = default_system
self.max_length = max_length
self.truncation_strategy = truncation_strategy
self.model = kwargs.get('model', None)
self.use_loss_scale = kwargs.get('use_loss_scale', False)
self.response_loss_scale_map = kwargs.get('loss_scale_map', None)
self.query_loss_scale_map = None
if self.response_loss_scale_map is not None:
if 'query' in self.response_loss_scale_map and isinstance(self.response_loss_scale_map['query'], dict):
self.query_loss_scale_map = self.response_loss_scale_map['query']
if 'response' in self.response_loss_scale_map and isinstance(self.response_loss_scale_map['response'],
dict):
self.response_loss_scale_map = self.response_loss_scale_map['response']
self.sequence_parallel_size = kwargs.get('sequence_parallel_size', 1)
for key in ['prefix', 'prompt', 'chat_sep', 'suffix', 'system_prefix']:
value = getattr(self, key)
value = self._preprocess_prompt(tokenizer, value)
setattr(self, key, value)
def check_example(self, example: Dict[str, Any]) -> None:
pass
def add_default_tags(self, example: Dict[str, Any]) -> None:
history: History = deepcopy(example.get('history') or [])
query: str = example.get('query') or ''
for media_key, media_tag in [('videos', '<video_label>'), ('images', '<image>'), ('audios', '<audio_label>')]:
if example.get(media_key) and media_tag not in ('\n'.join([h[0] for h in history]) + f'\n{query}'):
infer_media_type = TEMPLATE_MAPPING[self.template_type].get('infer_media_type')
if infer_media_type == 'round':
assert len(example[media_key]) == len(history) + 1
for h, m in zip(history, example[media_key][:-1]):
if m:
h[0] = media_tag + h[0]
if example[media_key][-1]:
query = media_tag + query
else:
media_len = len([m for m in example[media_key] if m])
if history:
history[0][0] = media_tag * media_len + history[0][0]
else:
query = media_tag * media_len + query
example['query'] = query
example['history'] = history
def encode(self, example: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""return: inputs, tokenizer_kwargs"""
if not self._is_init:
raise ValueError(
'Template is not initialized, please use the `get_template` function to obtain the template.')
if example.get('images') and not isinstance(example['images'], (tuple, list)):
# change images field to list
example['images'] = [example['images']]
example = example.copy()
self.add_default_tags(example)
self.check_example(example)
if example.get('objects') and isinstance(example['objects'], str):
# reload grounding from str
example['objects'] = json.loads(example['objects'])
query: str = example.get('query') or ''
query_role: str = example.get('query_role') or 'user'
response: Optional[str] = example.get('response')
history: History = example.get('history') or []
history_roles: Optional[History] = example.get('history_roles')
system: Optional[str] = example.get('system', None)
template_type: Optional[str] = getattr(self, 'template_type', None)
tools: Union[List[Any], str] = example.get('tools') or []
is_multi_modal: bool = any([example.get(key) for key in Template.special_keys])
if len(history) > 0:
assert self.support_multi_round, (
f'The template does not support multi-round chat, template_type: {template_type}')
if system is None:
if self.use_default_system:
system = self.default_system
elif system == '':
system = None
else:
assert self.system_prefix is not None, (
f'The template does not support `system`, template_type: {template_type}')
if tools:
if isinstance(tools, str):
tools = json.loads(tools)
if system is None:
system = ''
system += get_tools_prompt(tools, self.tools_prompt)
if history_roles is None:
history_roles = [['user', 'assistant'] for _ in range(len(history))]
inputs, tokenizer_kwargs = self._encode(
query,
query_role,
response,
history,
history_roles,
system,
self.truncation_strategy,
auto_add_bos=self.auto_add_bos,
example=example,
is_multi_modal=is_multi_modal)
if inputs.get('labels') is None:
inputs.pop('loss_scale', None)
return inputs, tokenizer_kwargs
def _concat_context_list(
self,
context_list: List[Context],
res_context_list: List[Context], # inplace
loss_scale_list: List[float], # inplace
system: Optional[str] = None,
query: Optional[str] = None,
response: Optional[str] = None,
round0: Optional[int] = None) -> None:
# concat context list and replace placeholder
round1 = None
if round0 is not None:
round1 = str(round0 + 1)
round0 = str(round0)
for context in context_list:
if isinstance(context, str):
if '{{RESPONSE}}' == context:
assert response is not None
content_part, weight_part = calculate_loss_scale(query, response, self.use_loss_scale,
self.response_loss_scale_map,
self.query_loss_scale_map)
res_context_list.extend(content_part)
loss_scale_list.extend(weight_part)
continue
old_str_list = ['{{SYSTEM}}', '{{QUERY}}', '{{ROUND0}}', '{{ROUND1}}']
new_str_list = [system, query, round0, round1]
for (old_str, new_str) in zip(old_str_list, new_str_list):
if new_str is not None and old_str in context:
context = context.replace(old_str, new_str)
res_context_list.append(context)
loss_scale_list.append(0.0 if context not in self.suffix else 1.0)
def _simplify_context_list(self, context_list: List[Context], loss_scale_list: List[float],
**kwargs) -> Tuple[List[Context], List[float]]:
res: List[Context] = [] # result of context_list
res_loss_scale: List[float] = [] # result of loss_scale_list
temp: List[str] = []
temp_index: List[int] = []
is_multi_modal: bool = kwargs.pop('is_multi_modal', False)
if is_multi_modal:
context_list, loss_scale_list = self.split_special_tokens(context_list, loss_scale_list)
context_list, loss_scale_list = self.pre_tokenize(context_list, loss_scale_list, **kwargs)
for i, (context, loss_scale) in enumerate(zip(context_list, loss_scale_list)):
if isinstance(context, str) and loss_scale_list[i] == 0.0:
temp.append(context)
temp_index.append(i)
else:
if len(temp) > 0:
res.append(''.join(temp))
res_loss_scale.append(0.0)
temp.clear()
res.append(context)
res_loss_scale.append(loss_scale)
if len(temp) > 0:
res.append(''.join(temp))
res_loss_scale.append(0.0)
return res, res_loss_scale
@staticmethod
def split_special_tokens(context_list: List[Context],
loss_scale_list: List[float]) -> Tuple[List[Context], List[float]]:
from swift.utils.utils import split_str_parts_by
res: List[Context] = []
loss_scale_res: List[float] = []
from swift.llm.utils.utils import fetch_one
for context, loss_scale in zip(context_list, loss_scale_list):
contexts = []
if isinstance(fetch_one(context), str):
for d in split_str_parts_by(context, Template.special_tokens):
contexts.extend([d['key'], d['content']])
contexts = [c for c in contexts if c]
res.extend(contexts)
loss_scale_res.extend([loss_scale] * len(contexts))
else:
res.append(context)
loss_scale_res.append(loss_scale)
return res, loss_scale_res
def _tokenize(self, context, **tokenizer_kwargs):
return self.tokenizer(
context, return_attention_mask=False, add_special_tokens=False, **tokenizer_kwargs)['input_ids']
def replace_tag(self, media_type: Literal['image', 'video', 'audio'], index: int,
example: Dict[str, Any]) -> List[Context]:
if media_type == 'image':
return ['<image>']
if media_type == 'video':
return ['<video_label>']
if media_type == 'audio':
return ['<audio_label>']
def replace_object(self, index: int, example: Dict[str, Any]) -> List[Context]:
objects = example.get('objects')
if objects:
object_ = objects[index]
return [object_[0]]
else:
return ['<ref-object>']
def replace_box(self, index: int, example: Dict[str, Any]) -> List[Context]:
objects = example.get('objects')
if objects:
object_ = objects[index]
return [f'({object_[1][0]},{object_[1][1]}),({object_[1][2]},{object_[1][3]})']
else:
return ['<bbox>']
def pre_tokenize(self, context_list: List[Context], loss_scale_list: List[float],
**kwargs) -> Tuple[List[Context], List[float]]:
# replace tag/object/box
example = kwargs.get('example') # get x_index
res: List[Context] = [] # result of context_list
res_loss_scale: List[float] = [] # result of loss_scale_list
for context, loss_scale in zip(context_list, loss_scale_list):
if context == '<image>':
c_list = self.replace_tag('image', example.get('image_index', 0), example)
example['image_index'] = example.get('image_index', 0) + 1
elif context == '<video_label>':
c_list = self.replace_tag('video', example.get('video_index', 0), example)
example['video_index'] = example.get('video_index', 0) + 1
elif context == '<audio_label>':
c_list = self.replace_tag('audio', example.get('audio_index', 0), example)
example['audio_index'] = example.get('audio_index', 0) + 1
elif context == '<ref-object>':
c_list = self.replace_object(example.get('object_index', 0), example)
example['object_index'] = example.get('object_index', 0) + 1
elif context == '<bbox>':
c_list = self.replace_box(example.get('box_index', 0), example)
example['box_index'] = example.get('box_index', 0) + 1
else:
c_list = [context]
res += c_list
res_loss_scale += [loss_scale] * len(c_list)
return res, res_loss_scale
def _encode_context_list(self, context_list: List[Context],
loss_scale_list: List[float]) -> Tuple[List[int], List[int], List[float], Dict[str, Any]]:
"""return: input_ids, labels, tokenizer_kwargs"""
input_ids: List[int] = []
labels: List[int] = []
loss_scale: List[float] = []
tokenizer_kwargs = {}
for i, (context, loss_weight) in enumerate(zip(context_list, loss_scale_list)):
if isinstance(context, str):
# tokenizer_kwargs is the returned tokenizer_kwargs,
# while curr_tokenizer_kwargs is the tokenizer_kwargs for the current context.
curr_tokenizer_kwargs = self._get_tokenizer_kwargs(context)
self._concat_tokenizer_kwargs(tokenizer_kwargs, curr_tokenizer_kwargs)
token_list = self._tokenize(context, **curr_tokenizer_kwargs)
else:
token_list = context
input_ids += token_list
if loss_scale_list[i] > 0.0:
labels += token_list
else:
labels += [-100] * len(token_list)
loss_scale.extend([loss_weight] * len(token_list))
return input_ids, labels, loss_scale, tokenizer_kwargs
def _encode(self,
query: str,
query_role: str,
response: Optional[str],
history: History,
history_roles: History,
system: Optional[str],
truncation_strategy: str,
auto_add_bos: bool = False,
**kwargs) -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""
return: inputs, tokenizer_kwargs
"""
history = history.copy()
res_context_list: List[Context] = []
loss_scale_list: List[float] = []
if auto_add_bos:
bos_token_id = self.tokenizer.bos_token_id
if isinstance(bos_token_id, int) and bos_token_id in self.tokenizer.encode(''):
res_context_list.append([bos_token_id])
loss_scale_list.append(0.)
if system is None:
prefix = self.prefix
else:
prefix = self.system_prefix
self._concat_context_list(prefix, res_context_list, loss_scale_list, system=system)
history.append([query, response])
history_roles.append([query_role, 'assistant'])
for i, ((q, r), (qr, rr)) in enumerate(zip(history, history_roles)):
context_list = self.tool_prompt.copy() if qr == 'tool' else self.prompt.copy()
if i < len(history) - 1:
context_list.append('{{RESPONSE}}')
if history[i + 1][0]:
context_list += self.chat_sep
elif r is not None:
# last response
context_list.append('{{RESPONSE}}')
context_list += self.suffix
if q or r:
self._concat_context_list(
context_list, res_context_list, loss_scale_list, query=q, response=r, round0=i)
res_context_list, loss_scale_list = self._simplify_context_list(res_context_list, loss_scale_list, **kwargs)
input_ids, labels, loss_scale, tokenizer_kwargs = self._encode_context_list(res_context_list, loss_scale_list)
if response is None:
labels = None
if self.max_length is not None:
if truncation_strategy == 'delete' and len(input_ids) > self.max_length:
return {}, {}
input_ids = input_ids[-self.max_length:]
if labels is not None:
labels = labels[-self.max_length:]
if loss_scale is not None:
loss_scale = loss_scale[-self.max_length:]
inputs = {
'input_ids': input_ids,
'labels': labels,
}
if self.use_loss_scale:
inputs['loss_scale'] = loss_scale
return inputs, tokenizer_kwargs
def _get_tokenizer_kwargs(self, context: str) -> Dict[str, Any]:
"""return: curr_tokenizer_kwargs"""
return {}
def _concat_tokenizer_kwargs(self, tokenizer_kwargs: Dict[str, Any], curr_tokenizer_kwargs: Dict[str, Any]) -> None:
assert len(tokenizer_kwargs) == 0
def data_collator(self, batch: List[Dict[str, Any]], padding_to: Optional[int] = None) -> Dict[str, Any]:
"""
Args:
batch(`List[Dict[str, Any]]`): The input data in batch
padding_to(`int`, optional): Whether padding the batch to a fixed length, if none, the batch
will be padded to the `longest`
"""
tokenizer = self.tokenizer
assert tokenizer.pad_token_id is not None
inputs_embeds, input_ids = None, None
if 'inputs_embeds' in batch[0]:
inputs_embeds = [b['inputs_embeds'] for b in batch]
attention_mask = [
torch.ones((inputs_embeds[i].shape[0]), dtype=torch.int64) for i in range(len(inputs_embeds))
]
else:
input_ids = [torch.tensor(b['input_ids']) for b in batch]
attention_mask = [torch.ones(len(input_ids[i]), dtype=torch.int64) for i in range(len(input_ids))]
labels = [torch.tensor(b['labels']) for b in batch]
loss_scale = [torch.tensor(b['loss_scale']) for b in batch] if 'loss_scale' in batch[0] else None
if padding_to is not None:
assert input_ids is not None # inputs_embeds not support padding_to
padding_len = padding_to - input_ids[0].shape[-1]
if padding_len > 0:
input_ids[0] = F.pad(input_ids[0], (0, padding_len), 'constant', tokenizer.pad_token_id)
attention_mask[0] = F.pad(attention_mask[0], (0, padding_len), 'constant', 0)
labels[0] = F.pad(labels[0], (0, padding_len), 'constant', -100)
if loss_scale:
loss_scale[0] = F.pad(loss_scale[0], (0, padding_to - labels[0].shape[-1]), 'constant', 0.)
if input_ids is None:
inputs_embeds = pad_sequence(inputs_embeds, batch_first=True, padding_value=0)
else:
input_ids = pad_sequence(input_ids, batch_first=True, padding_value=tokenizer.pad_token_id)
attention_mask = pad_sequence(attention_mask, batch_first=True, padding_value=0)
if loss_scale:
loss_scale = pad_sequence(loss_scale, batch_first=True, padding_value=0.)
labels = pad_sequence(labels, batch_first=True, padding_value=-100)
if use_torchacc():
rank, _, world_size, _ = get_dist_setting()
input_ids, attention_mask, labels, loss_scale = pad_and_split_batch(padding_to, input_ids, attention_mask,
labels, loss_scale, self.max_length,
self.tokenizer, rank, world_size)
if input_ids is not None:
bs, seq_len = input_ids.shape
position_ids = torch.arange(seq_len).unsqueeze(0).long().repeat(bs, 1)
if self.sequence_parallel_size > 1:
from swift.trainers.xtuner import get_xtuner_sequence_parallel_world_size
if get_xtuner_sequence_parallel_world_size() > 1:
from swift.trainers.xtuner import pad_and_split_for_sequence_parallel
input_ids, labels, position_ids, attention_mask, loss_scale = \
pad_and_split_for_sequence_parallel(
tokenizer, input_ids, labels, position_ids, attention_mask, loss_scale)
res = {
'attention_mask': attention_mask,
'labels': labels,
}
if inputs_embeds is not None:
res['inputs_embeds'] = inputs_embeds
else:
res['input_ids'] = input_ids
# multimodal
pixel_values = [b['pixel_values'] for b in batch if b.get('pixel_values') is not None]
if len(pixel_values) > 0:
res['pixel_values'] = torch.concat(pixel_values)
image_sizes = [b['image_sizes'] for b in batch if b.get('image_sizes') is not None]
if len(image_sizes) > 0:
res['image_sizes'] = torch.concat(image_sizes)
if loss_scale is not None:
res['loss_scale'] = loss_scale
return res
@staticmethod
def get_generate_ids(generate_ids: Tensor, input_token_len: int) -> List[int]:
return generate_ids[0, input_token_len:].tolist()
@staticmethod
def _is_chinese_char(cp: int) -> bool:
"""Checks whether CP is the codepoint of a CJK character."""
# copy from transformers.generation.streamers.TextStreamer
if ((0x4E00 <= cp <= 0x9FFF) or (0x3400 <= cp <= 0x4DBF) or (0x20000 <= cp <= 0x2A6DF)
or (0x2A700 <= cp <= 0x2B73F) or (0x2B740 <= cp <= 0x2B81F) or (0x2B820 <= cp <= 0x2CEAF)
or (0xF900 <= cp <= 0xFAFF) or (0x2F800 <= cp <= 0x2FA1F)):
return True
return False
@classmethod
def _get_safe_print_idx(cls, response: str, print_idx: int, is_finished: bool = False) -> int:
if is_finished:
return len(response)
if response.endswith('\n') or len(response) > 0 and cls._is_chinese_char(ord(response[-1])):
print_idx = len(response)
else:
print_idx = max(response.rfind(' ') + 1, print_idx)
return print_idx
def generate_ids_to_response(
self,
generate_ids: List[int],
is_finished: bool = True,
*,
tokenizer_kwargs: Optional[Dict[str, Any]] = None,
# only stream=True
return_delta: bool = False,
print_idx: Optional[List[int]] = None,
first_num_space: Optional[List[int]] = None,
):
if tokenizer_kwargs is None:
tokenizer_kwargs = {}
tokenizer = self.tokenizer
# avoid printing template.suffix[-1])
if isinstance(self.suffix[-1], list) and (not is_finished or is_finished
and generate_ids[-len(self.suffix[-1]):] == self.suffix[-1]):
generate_ids = generate_ids[:-len(self.suffix[-1])]
response = tokenizer.decode(generate_ids, **tokenizer_kwargs)
if first_num_space is not None:
# Avoid the occurrence of repeated words in sentence.
res_fns = first_num_space # res_first_num_space
first_num_space = first_num_space[0]
cur_num_space = len(response) - len(response.lstrip(' '))
if not is_finished and first_num_space == -1:
first_num_space = cur_num_space
res_fns[0] = first_num_space
if cur_num_space < first_num_space:
response = ' ' * (first_num_space - cur_num_space) + response
elif cur_num_space > first_num_space:
response = response[cur_num_space - first_num_space:]
if isinstance(self.suffix[-1],
str) and (not is_finished or is_finished and response[-len(self.suffix[-1]):] == self.suffix[-1]):
response = response[:-len(self.suffix[-1])]
if print_idx is not None:
old_print_idx = print_idx[0]
if not is_finished:
# avoid printing incomplete words
print_idx[0] = self._get_safe_print_idx(response, print_idx[0])
response = response[:print_idx[0]]
if return_delta:
response = response[old_print_idx:]
else:
assert is_finished and not return_delta
return response
def post_process_generate_response(self, response: str, example: dict) -> str:
return response
def register_template(template_type: str, template: Template, *, exist_ok: bool = False, **kwargs) -> None:
if not exist_ok and template_type in TEMPLATE_MAPPING:
raise ValueError(f'The `{template_type}` has already been registered in the TEMPLATE_MAPPING.')
template.template_type = template_type
template_info = {'template': template, **kwargs}
TEMPLATE_MAPPING[template_type] = template_info
register_template(
TemplateType.default,
Template([], ['### Human:\n{{QUERY}}\n\n### Assistant:\n'], ['\n\n'], [['eos_token_id']], DEFAULT_SYSTEM,
['{{SYSTEM}}\n\n']))
# You can set the query as '' to serve as a template for pre-training.
class DefaultGenerationTemplate(Template):
def __init__(self):
super().__init__([], ['{{QUERY}}'], None, [['eos_token_id']], auto_add_bos=True)
register_template(TemplateType.default_generation, DefaultGenerationTemplate(), is_generation=True)
register_template(
TemplateType.default_generation_bos,
Template([['bos_token_id']], ['{{QUERY}}'], None, [['eos_token_id']]),
is_generation=True)
class QwenTemplate(Template):
def __init__(self, auto_add_bos: bool = False):
super().__init__([], ['<|im_start|>user\n{{QUERY}}<|im_end|>\n<|im_start|>assistant\n'], ['<|im_end|>\n'],
['<|im_end|>'],
DEFAULT_SYSTEM, ['<|im_start|>system\n{{SYSTEM}}<|im_end|>\n'],
auto_add_bos=auto_add_bos)
class QwenVLTemplate(QwenTemplate):
def check_example(self, example):
images = example.get('images') or []
from swift.llm.utils.utils import fetch_one
assert not images or isinstance(fetch_one(images), str), 'QwenVL only supports datasets with images paths!'
def replace_tag(self, media_type: Literal['image', 'video', 'audio'], index: int,
example: Dict[str, Any]) -> List[Context]:
assert media_type == 'image'
images = example.get('images') or []
image = images[index]
assert isinstance(image, str)
return [f'<img>{image}</img>']
def replace_object(self, index: int, example: Dict[str, Any]) -> List[Context]:
objects = example['objects']
object_ = objects[index]
return [f'<ref>{object_[0]}</ref>']
def replace_box(self, index: int, example: Dict[str, Any]) -> List[Context]:
objects = example['objects']
object_ = objects[index]
return [f'<box>({object_[1][0]},{object_[1][1]}),({object_[1][2]},{object_[1][3]})</box>']
register_template(TemplateType.qwen, QwenTemplate())
register_template(TemplateType.qwen_vl, QwenVLTemplate())
register_template(TemplateType.chatml, QwenTemplate(auto_add_bos=True))
register_template(
TemplateType.modelscope_agent,
Template([], [' \n\n<|user|>:{{QUERY}} \n\n<|assistant|>:'], [], [' \n\n</s>'], DEFAULT_SYSTEM,
[' \n\n<|system|>:{{SYSTEM}}']))
class _QwenAudioTemplateMixin:
def encode(self, example: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any]]:
inputs, tokenizer_kwargs = super().encode(example)
if len(inputs) == 0:
return inputs, tokenizer_kwargs
inputs.pop('loss_scale', None)
inputs.update(tokenizer_kwargs)
return inputs, tokenizer_kwargs
def _get_tokenizer_kwargs(self, context: str) -> Dict[str, Any]:
return {'audio_info': self.tokenizer.process_audio(context)}
def _concat_tokenizer_kwargs(self, tokenizer_kwargs: Dict[str, Any], curr_tokenizer_kwargs: Dict[str, Any]) -> None:
audio_info = curr_tokenizer_kwargs.get('audio_info')
old_audio_info = tokenizer_kwargs.get('audio_info')
if old_audio_info is None:
tokenizer_kwargs['audio_info'] = audio_info
elif audio_info is not None:
for k in ['input_audios', 'input_audio_lengths']:
old_audio_info[k] = torch.concat([old_audio_info[k], audio_info[k]], dim=0)
for k in ['audio_span_tokens', 'audio_urls']:
old_audio_info[k] = old_audio_info[k] + audio_info[k]
def data_collator(self, batch: List[Dict[str, Any]], padding_to: Optional[int] = None) -> Dict[str, Any]:
res = super().data_collator(batch, padding_to)
if batch[0].get('audio_info') is not None:
res['audio_info'] = [b['audio_info'] for b in batch]
return res
class QwenAudioTemplate(_QwenAudioTemplateMixin, QwenTemplate):
pass
class QwenAudioGenerationTemplate(_QwenAudioTemplateMixin, DefaultGenerationTemplate):
pass
register_template(TemplateType.qwen_audio, QwenAudioTemplate(), lazy_tokenize=True)
register_template(
TemplateType.qwen_audio_generation, QwenAudioGenerationTemplate(), lazy_tokenize=True, is_generation=True)
register_template(
TemplateType.yi,
Template([], ['<|im_start|>user\n{{QUERY}}<|im_end|>\n<|im_start|>assistant\n'], ['<|im_end|>\n'], ['<|im_end|>'],
None, ['<|im_start|>system\n{{SYSTEM}}<|im_end|>\n']))
register_template(
TemplateType.yi1_5,
Template([], ['<|im_start|>user\n{{QUERY}}<|im_end|> \n<|im_start|>assistant\n'], ['<|im_end|>\n'], ['<|im_end|>'],
None, ['{{SYSTEM}}']))
yi_vl_default_system = (
'This is a chat between an inquisitive human and an AI assistant. Assume the role of the AI assistant. '
"Read all the images carefully, and respond to the human's questions with informative, "
'helpful, detailed and polite answers. '
'这是一个好奇的人类和一个人工智能助手之间的对话。假设你扮演这个AI助手的角色。'
'仔细阅读所有的图像,并对人类的问题做出信息丰富、有帮助、详细的和礼貌的回答。')
def _read_from_path(img_path: Union[str, 'PIL.Image.Image']) -> 'PIL.Image.Image':
from PIL import Image, UnidentifiedImageError
import os
import base64
import binascii
if isinstance(img_path, str):
img_path = img_path.strip()
if img_path.startswith('http'):
content = requests.get(img_path).content
image = Image.open(BytesIO(content))
elif os.path.exists(img_path):
image = Image.open(img_path)
else: # base64_str
try:
image_data = base64.b64decode(img_path)
image = Image.open(BytesIO(image_data))
except (binascii.Error, UnidentifiedImageError) as error:
raise ValueError(f'invalid image: {error}')
else:
image = img_path
if image.mode != 'RGB':
image = image.convert('RGB')
return image
def _read_batch(path_list: List[Union[str, 'PIL.Image.Image', None]]) -> List['PIL.Image.Image']:
res = []
for path in path_list:
if path is None: # ignore None
continue
res.append(_read_from_path(path))
return res
class YiVLTemplate(Template):
def replace_tag(self, media_type, index, example) -> List[Context]:
assert media_type == 'image'
return [[-200], '\n']
def encode(self, example: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any]]:
inputs, _ = super().encode(example)
if len(inputs) == 0:
return inputs, {}
inputs.pop('loss_scale', None)
from llava.mm_utils import expand2square
model = self.model.model
if not hasattr(model, 'vision_tower'):
model = model.model
image_processor = model.vision_tower.image_processor
images_path = example.get('images') or []
images = _read_batch(images_path)
for i, image in enumerate(images):
background_color = tuple(int(x * 255) for x in image_processor.image_mean)
image = expand2square(image, background_color)
images[i] = image
if images:
image_tensor = image_processor.preprocess(images, return_tensors='pt')['pixel_values']
inputs['images'] = image_tensor.to(model.dtype)
return inputs, {}
def data_collator(self, batch: List[Dict[str, Any]], padding_to: Optional[int] = None) -> Dict[str, Any]:
res = super().data_collator(batch, padding_to)
images = [b['images'] for b in batch if 'images' in b]
if images:
res['images'] = torch.concat(images)
has_images = [(b == -200).sum() for b in res['input_ids']]
assert all([
h > 0 for h in has_images
]) or not any([h > 0
for h in has_images]), 'YIVL does not support mix-batch nlp dataset and multi-modal dataset'
return res
class GLMTemplate(Template):
def _init_template(self, tokenizer: PreTrainedTokenizerBase, *args, **kwargs) -> None:
res = super()._init_template(tokenizer, *args, **kwargs)
token_list = tokenizer.encode('')
self.prefix.insert(0, token_list)
if self.system_prefix is not None:
self.system_prefix.insert(0, token_list)
return res
class GLM4VTemplate(GLMTemplate):
def __init__(self):
super().__init__([], ['<|user|>\n{{QUERY}}<|assistant|>'], [], ['<|endoftext|>'], None,
['<|system|>\n{{SYSTEM}}'])
def check_example(self, example):
images = example.get('images') or []
assert len(images) <= 1
def replace_tag(self, media_type: Literal['image', 'video', 'audio'], index, example) -> List[Context]:
assert media_type == 'image'
return [[-100]]
def encode(self, example: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any]]:
from .utils import history_to_messages
inputs, _ = super().encode(example)
if len(inputs) == 0:
return inputs, {}
input_ids = inputs['input_ids']
labels = inputs['labels']
idx_list = _findall(input_ids, -100)
if idx_list:
idx = idx_list[0]
images_path = example.get('images') or []
image = _read_from_path(images_path[0])
placeholder = '<|begin_of_image|><|endoftext|><|end_of_image|>'
placeholder_id = self.tokenizer.encode(placeholder, add_special_tokens=False)
input_ids = (input_ids[:idx] + placeholder_id + input_ids[idx + 1:])
if labels is not None:
labels = (labels[:idx] + [-100] * len(placeholder_id) + labels[idx + 1:])
messages = history_to_messages(example.get('history') or [], example['query'], example.get('system'))
messages[0]['image'] = image
inputs2: Dict[str, Any] = self.tokenizer.apply_chat_template(messages, return_dict=True)
inputs['images'] = inputs2['images']
inputs['input_ids'] = input_ids
inputs['labels'] = labels
return inputs, {}
def data_collator(self, batch: List[Dict[str, Any]], padding_to: Optional[int] = None) -> Dict[str, Any]:
res = super().data_collator(batch, padding_to)
pad_len = res['labels'].shape[1] - res['input_ids'].shape[1]
res['attention_mask'] = F.pad(res['attention_mask'], (pad_len, 0), 'constant', 1)
images = [b['images'] for b in batch if 'images' in b]
if images:
res['images'] = torch.concat(images)
return res
register_template(TemplateType.glm4v, GLM4VTemplate(), infer_media_type='dialogue', lazy_tokenize=True, use_model=True)