-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathangle.py
1680 lines (1477 loc) · 68.5 KB
/
angle.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
# -*- coding: utf-8 -*-
import os
import re
import sys
import json
import copy
import math
from functools import partial
from typing import Any, Dict, Optional, List, Union, Tuple, Callable
from dataclasses import dataclass
import scipy
import scipy.stats
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import bitsandbytes as bnb
from tqdm import tqdm
from boltons.iterutils import chunked_iter
from datasets import Dataset
from transformers import (
AutoModelForCausalLM, AutoModel, AutoTokenizer,
PreTrainedModel, Trainer, TrainingArguments,
TrainerCallback, BitsAndBytesConfig
)
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
from transformers.utils import PaddingStrategy
from huggingface_hub import repo_exists
from peft import (
get_peft_model, LoraConfig, TaskType, PeftModel,
prepare_model_for_kbit_training,
)
from peft.tuners.lora import LoraLayer
from .utils import logger
DEFAULT_LLM_PATTERNS = [r'.*llama.*', r'.*qwen.*', r'.*baichuan.*', r'.*mistral.*']
def set_device() -> str:
"""
Set device automatically
:return: str, device name
"""
if torch.cuda.is_available():
return 'cuda'
elif torch.backends.mps.is_available():
return 'mps'
return 'cpu'
def find_all_linear_names(model: PreTrainedModel, linear_type: Optional[object] = None) -> List[str]:
"""
Find all linear layer names
:param model: PreTrainedModel
:param linear_type: Optional[object] = None, linear type, such as nn.Linear and bnb.nn.Linear4bit.
:return: List[str], linear layer names
"""
if linear_type is None:
linear_type = nn.Linear
lora_module_names = set()
for name, module in model.named_modules():
if isinstance(module, linear_type):
names = name.split('.')
lora_module_names.add(names[0] if len(names) == 1 else names[-1])
if 'lm_head' in lora_module_names:
lora_module_names.remove('lm_head')
return list(lora_module_names)
def categorical_crossentropy(y_true: torch.Tensor, y_pred: torch.Tensor, from_logits: bool = True) -> torch.Tensor:
"""
Compute categorical crossentropy
:param y_true: torch.Tensor, ground truth
:param y_pred: torch.Tensor, model output
:param from_logits: bool, `True` means y_pred has not transformed by softmax, default True
:return: torch.Tensor, loss value
"""
if from_logits:
return -(F.log_softmax(y_pred, dim=1) * y_true).sum(dim=1)
return -(torch.log(y_pred, dim=1) * y_true).sum(dim=1)
def cosine_loss(y_true: torch.Tensor, y_pred: torch.Tensor, tau: float = 20.0) -> torch.Tensor:
"""
Compute cosine loss
:param y_true: torch.Tensor, ground truth.
The y_true must be zigzag style, such as [x[0][0], x[0][1], x[1][0], x[1][1], ...], where (x[0][0], x[0][1]) stands for a pair.
:param y_pred: torch.Tensor, model output.
The y_pred must be zigzag style, such as [o[0][0], o[0][1], o[1][0], o[1][1], ...], where (o[0][0], o[0][1]) stands for a pair.
:param tau: float, scale factor, default 20
:return: torch.Tensor, loss value
""" # NOQA
# modified from: https://github.com/bojone/CoSENT/blob/124c368efc8a4b179469be99cb6e62e1f2949d39/cosent.py#L79
y_true = y_true[::2, 0]
y_true = (y_true[:, None] < y_true[None, :]).float()
y_pred = F.normalize(y_pred, p=2, dim=1)
y_pred = torch.sum(y_pred[::2] * y_pred[1::2], dim=1) * tau
y_pred = y_pred[:, None] - y_pred[None, :]
y_pred = (y_pred - (1 - y_true) * 1e12).view(-1)
zero = torch.Tensor([0]).to(y_pred.device)
y_pred = torch.concat((zero, y_pred), dim=0)
return torch.logsumexp(y_pred, dim=0)
def angle_loss(y_true: torch.Tensor, y_pred: torch.Tensor, tau: float = 1.0, pooling_strategy: str = 'sum'):
"""
Compute angle loss
:param y_true: torch.Tensor, ground truth.
The y_true must be zigzag style, such as [x[0][0], x[0][1], x[1][0], x[1][1], ...], where (x[0][0], x[0][1]) stands for a pair.
:param y_pred: torch.Tensor, model output.
The y_pred must be zigzag style, such as [o[0][0], o[0][1], o[1][0], o[1][1], ...], where (o[0][0], o[0][1]) stands for a pair.
:param tau: float, scale factor, default 1.0
:return: torch.Tensor, loss value
""" # NOQA
y_true = y_true[::2, 0]
y_true = (y_true[:, None] < y_true[None, :]).float()
y_pred_re, y_pred_im = torch.chunk(y_pred, 2, dim=1)
a = y_pred_re[::2]
b = y_pred_im[::2]
c = y_pred_re[1::2]
d = y_pred_im[1::2]
# (a+bi) / (c+di)
# = ((a+bi) * (c-di)) / ((c+di) * (c-di))
# = ((ac + bd) + i(bc - ad)) / (c^2 + d^2)
# = (ac + bd) / (c^2 + d^2) + i(bc - ad)/(c^2 + d^2)
z = torch.sum(c**2 + d**2, dim=1, keepdim=True)
re = (a * c + b * d) / z
im = (b * c - a * d) / z
dz = torch.sum(a**2 + b**2, dim=1, keepdim=True)**0.5
dw = torch.sum(c**2 + d**2, dim=1, keepdim=True)**0.5
re /= (dz / dw)
im /= (dz / dw)
y_pred = torch.concat((re, im), dim=1)
if pooling_strategy == 'sum':
pooling = torch.sum(y_pred, dim=1)
elif pooling_strategy == 'mean':
pooling = torch.mean(y_pred, dim=1)
else:
raise ValueError(f'Unsupported pooling strategy: {pooling_strategy}')
y_pred = torch.abs(pooling) * tau # absolute delta angle
y_pred = y_pred[:, None] - y_pred[None, :]
y_pred = (y_pred - (1 - y_true) * 1e12).view(-1)
zero = torch.Tensor([0]).to(y_pred.device)
y_pred = torch.concat((zero, y_pred), dim=0)
return torch.logsumexp(y_pred, dim=0)
def in_batch_negative_loss(y_true: torch.Tensor,
y_pred: torch.Tensor,
tau: float = 20.0,
negative_weights: float = 0.0) -> torch.Tensor:
"""
Compute in-batch negative loss, i.e., contrastive loss
:param y_true: torch.Tensor, ground truth.
The y_true must be zigzag style, such as [x[0][0], x[0][1], x[1][0], x[1][1], ...], where (x[0][0], x[0][1]) stands for a pair.
:param y_pred: torch.Tensor, model output.
The y_pred must be zigzag style, such as [o[0][0], o[0][1], o[1][0], o[1][1], ...], where (o[0][0], o[0][1]) stands for a pair.
:param tau: float, scale factor, default 20.0
:param negative_weights: float, negative weights, default 0.0
:return: torch.Tensor, loss value
""" # NOQA
device = y_true.device
def make_target_matrix(y_true: torch.Tensor):
idxs = torch.arange(0, y_pred.shape[0]).int().to(device)
y_true = y_true.int()
idxs_1 = idxs[None, :]
idxs_2 = (idxs + 1 - idxs % 2 * 2)[:, None]
idxs_1 *= y_true.T
idxs_1 += (y_true.T == 0).int() * -2
idxs_2 *= y_true
idxs_2 += (y_true == 0).int() * -1
y_true = (idxs_1 == idxs_2).float()
return y_true
neg_mask = make_target_matrix(y_true == 0)
y_true = make_target_matrix(y_true)
# compute similarity
y_pred = F.normalize(y_pred, dim=1, p=2)
similarities = y_pred @ y_pred.T # dot product
similarities = similarities - torch.eye(y_pred.shape[0]).to(device) * 1e12
similarities = similarities * tau
if negative_weights > 0:
similarities += neg_mask * negative_weights
return categorical_crossentropy(y_true, similarities, from_logits=True).mean()
def contrastive_with_negative_loss(
text: torch.Tensor,
pos: torch.Tensor,
neg: Optional[torch.Tensor] = None,
tau: float = 20.0) -> torch.Tensor:
"""
Compute contrastive with negative loss
:param text: torch.Tensor, text.
:param pos: torch.Tensor, positive samples of text.
:param neg: torch.Tensor, negative samples of text.
:param tau: float, scale factor, default 20.0
:return: torch.Tensor, loss value
"""
target = torch.cat((pos, neg), dim=0) if neg is not None else pos # (2B, D)
q_norm = torch.nn.functional.normalize(text, p=2, dim=1) # (B, D)
t_norm = torch.nn.functional.normalize(target, p=2, dim=1) # (2B, D)
scores = torch.mm(q_norm, t_norm.transpose(0, 1)) * tau # (B, 2B)
labels = torch.tensor(
range(len(scores)), dtype=torch.long, device=scores.device
)
return nn.CrossEntropyLoss()(scores, labels)
def compute_corrcoef(x: np.ndarray, y: np.ndarray) -> float:
"""
Compute correlation coefficients
:param x: np.ndarry, x array
:param y: np.ndarry, y array
:return: float
"""
return scipy.stats.spearmanr(x, y).correlation
def l2_normalize(arr: np.ndarray) -> np.ndarray:
"""
Normalize array using L2
:param arr: np.ndarray, input array
:return: np.ndarray
"""
norms = (arr**2).sum(axis=1, keepdims=True)**0.5
return arr / np.clip(norms, 1e-8, np.inf)
def optimal_threshold(y_true: np.ndarray, y_pred: np.ndarray) -> Tuple[float, float]:
"""
Compute optimal threshold
:param y_true: np.ndarray, y_true
:param y_pred: np.ndarray, y_true
:return: Tuple[float, float]
"""
loss = lambda t: -np.mean((y_true > 0.5) == (y_pred > np.tanh(t))) # NOQA
result = scipy.optimize.minimize(loss, 1, method='Powell')
return np.tanh(result.x), -result.fun
def check_llm(model_name_or_path: str, llm_regex_patterns: List[str] = None) -> bool:
if llm_regex_patterns is not None:
llm_regex_patterns += DEFAULT_LLM_PATTERNS
else:
llm_regex_patterns = DEFAULT_LLM_PATTERNS
model_name_or_path = model_name_or_path.lower()
for pattern in llm_regex_patterns:
if re.match(pattern, model_name_or_path):
return True
return False
def get_pooling(outputs: torch.Tensor,
inputs: Dict,
pooling_strategy: str,
padding_strategy: str = 'right') -> torch.Tensor:
""" Pooling the model outputs.
:param outputs: torch.Tensor. Model outputs (without pooling)
:param inputs: Dict. Model inputs
:param pooling_strategy: str. Pooling strategy ['cls', 'cls_avg', 'cls_max', 'last', 'avg', 'max', 'all', index]
:param padding_strategy: str. Padding strategy of tokenizers (`left` or `right`).
It can be obtained by `tokenizer.padding_side`.
"""
if pooling_strategy == 'cls':
outputs = outputs[:, 0]
elif pooling_strategy == 'cls_avg':
avg = torch.sum(
outputs * inputs["attention_mask"][:, :, None], dim=1) / torch.sum(inputs["attention_mask"])
outputs = (outputs[:, 0] + avg) / 2.0
elif pooling_strategy == 'cls_max':
maximum, _ = torch.max(outputs * inputs["attention_mask"][:, :, None], dim=1)
outputs = (outputs[:, 0] + maximum) / 2.0
elif pooling_strategy == 'last':
batch_size = inputs['input_ids'].shape[0]
sequence_lengths = -1 if padding_strategy == 'left' else inputs["attention_mask"].sum(dim=1) - 1
outputs = outputs[torch.arange(batch_size, device=outputs.device), sequence_lengths]
elif pooling_strategy == 'avg':
outputs = torch.sum(
outputs * inputs["attention_mask"][:, :, None], dim=1) / torch.sum(inputs["attention_mask"])
elif pooling_strategy == 'max':
outputs, _ = torch.max(outputs * inputs["attention_mask"][:, :, None], dim=1)
elif pooling_strategy == 'all':
# keep outputs
pass
elif isinstance(pooling_strategy, int) or pooling_strategy.isnumeric():
# index
outputs = outputs[:, int(pooling_strategy)]
else:
raise NotImplementedError(
'please specify pooling_strategy from [`cls`, `last`, `avg`, `max`, `last_avg`, `all`, int]')
return outputs
class Prompts:
"""
Predefined prompts. Follow the model usage to choose the corresponding prompt.
Example::
from angle_emb import Prompts
# list all pre-defined prompts
print(Prompts.list_prompts())
# set prompt
angle.encode(*, prompt=Prompts.A)
"""
A = 'Summarize sentence "{text}" in one word:"'
B = 'You can only output one word. Summarize "{text}":"'
C = 'Represent this sentence for searching relevant passages: {text}'
@classmethod
def list_prompts(cls):
for key, val in Prompts.__dict__.items():
if key.startswith('_') or key == 'list_prompts':
continue
print(f'Prompts.{key}', '=', f"'{val}'")
class DatasetFormats:
"""
Predefined Data Formats.
Check all available formats:
from angle_emb import DatasetFormats
print(DatasetFormats.list_formats())
"""
"""
format A: text1,text2,label
input format: [
text1[0],
text2[0],
text1[1],
text2[1],
...
]
label format: [
label[0],
label[0],
label[1],
label[1],
...
]
"""
A = 'text1,text2,label'
"""
format B: text,positive,negative
input format: [
text[0],
positive[0],
negative[0],
text[1],
positive[1],
negative[1],
...
]
"""
B = 'text,positive,negative'
"""
format C: text,positive
input format: [
text[0],
positive[0],
text[1],
positive[1],
...
]
"""
C = 'text,positive'
@classmethod
def list_formats(cls):
for key, val in DatasetFormats.__dict__.items():
if key.startswith('_') or key == 'list_formats':
continue
print(f'DatasetFormats.{key}', '=', f"'{val}'")
class AngleDataTokenizer:
"""
Tokenize data using AngleDataTokenizer.
:param tokenizer: PreTrainedTokenizerBase. Tokenizer
:param max_length: Optional[int]. Specify max length
:param prompt_template: Optional[str], set prompt template, it will be applied to all input texts. Default None
:param extra_columns: Optional[List[str]].
If providing multiple placeholders in prompt_template, specify their name via extra_columns. Default None
:param dataset_format: Optional[str]. Specify dataset_format from DatasetFormats. Default None.
It will automatically detect the dataset format.
:param end_with_eos: bool. Specify whether ends with the eos token. Default False.
Example::
from datasets import load_dataset
from angle_emb import AnglE, AngleDataTokenizer
# define dataset
ds = load_dataset('your_dataset')
# define angle
angle = AnglE(*args, **kwargs)
# tokenize data
train_ds = ds['train'].shuffle().map(AngleDataTokenizer(angle.tokenizer, angle.max_length), num_proc=8)
valid_ds = ds['validation'].map(AngleDataTokenizer(angle.tokenizer, angle.max_length), num_proc=8)
"""
def __init__(self,
tokenizer: PreTrainedTokenizerBase,
max_length: Optional[int] = None,
prompt_template: Optional[str] = None,
template_placeholders: Optional[List[str]] = None,
extra_columns: Optional[List[str]] = None,
dataset_format: Optional[str] = None,
end_with_eos: bool = False):
self.tokenizer = tokenizer
self.max_length = max_length
self.prompt_template = prompt_template
self.prompt_template_tok = None
self.extra_columns = extra_columns
self.dataset_format = dataset_format
self.end_with_eos = end_with_eos
if template_placeholders is None:
template_placeholders = ['condition', 'text']
if prompt_template is not None:
re_placeholder = re.compile(r'\{(%s)\}' % '|'.join(template_placeholders))
self.prompt_template_tok = self.tokenizer(re_placeholder.sub('', prompt_template))
@staticmethod
def fix_bad_data(token_ids, prompt_ids):
bad_index = -1
for idx in range(len(token_ids) - 1, -1, -1):
try:
bad_index = prompt_ids.index(token_ids[idx])
except ValueError:
break
if bad_index == -1:
return token_ids
# print('bad index:', prompt_ids[bad_index])
to_fix_ids = prompt_ids[bad_index:]
return token_ids[:len(token_ids) - len(to_fix_ids)] + to_fix_ids
def __call__(self, data: Dict) -> Dict:
if self.dataset_format is None:
if 'text1' in data and 'text2' in data and 'label' in data:
logger.info(f'Detect DatasetFormats.A: {DatasetFormats.A}')
self.dataset_format = DatasetFormats.A
elif 'text' in data and 'positive' in data and 'negative' in data:
self.dataset_format = DatasetFormats.B
logger.info(f'Detect DatasetFormats.B: {DatasetFormats.B}')
elif 'text' in data and 'positive' in data and 'negative' not in data and 'label' not in data:
self.dataset_format = DatasetFormats.C
logger.info(f'Detect DatasetFormats.C: {DatasetFormats.C}')
else:
raise NotImplementedError('Currently only support two dataset formats'
'DatasetFormats A: must include three columns: `text1`, `text2`, and `label`.'
'DatasetFormats B: mut include three columns: `text`, `positive`, `negative`'
'DatasetFormats C: mut include three columns: `text`, `positive`')
text_columns = None
if self.dataset_format == DatasetFormats.A:
text_columns = ['text1', 'text2']
elif self.dataset_format == DatasetFormats.B:
text_columns = ['text', 'positive', 'negative']
elif self.dataset_format == DatasetFormats.C:
text_columns = ['text', 'positive']
extra_length = 0
extra_placeholder = {}
if self.extra_columns is not None:
for key, val in data.items():
if key not in self.extra_columns:
continue
extra_placeholder[key] = val
extra_length += len(self.tokenizer(val, add_special_tokens=False)['input_ids'])
if self.end_with_eos:
extra_length += 1
if self.prompt_template_tok is not None:
max_length = self.max_length - len(self.prompt_template_tok['input_ids']) - extra_length
for text_column in text_columns:
tok = self.tokenizer(data[text_column],
max_length=max_length,
truncation=True,
add_special_tokens=False)
data[text_column] = self.tokenizer.decode(tok['input_ids'])
data[text_column] = self.prompt_template.format(text=data[text_column], **extra_placeholder)
toks = []
for text_column in text_columns:
toks.append(self.tokenizer(data[text_column], max_length=self.max_length, truncation=True))
if self.prompt_template_tok is not None:
for tok in toks:
if tok['input_ids'][-1] != self.prompt_template_tok['input_ids'][-1]:
logger.info(f"data data: token ids={tok['input_ids']}, prompt_token_ids={self.prompt_template_tok['input_ids']}") # NOQA
tok['input_ids'] = self.fix_bad_data(tok['input_ids'], self.prompt_template_tok['input_ids'])
try:
assert len(tok['input_ids']) == len(tok['attention_mask'])
assert tok['input_ids'][-1] == self.prompt_template_tok['input_ids'][-1]
logger.info('fixed it ;)')
logger.info(f"new data, token ids={tok['input_ids']}, prompt_token_ids={self.prompt_template_tok['input_ids']}") # NOQA
except AssertionError:
logger.info('failed to fix it :( skip it...')
combined_tok = {}
seperate_ids = []
for idx, tok in enumerate(toks):
for key, val in tok.items():
if idx == 0:
combined_tok[key] = val
else:
combined_tok[key] += val
if key == 'input_ids':
seperate_ids += [idx] * len(val)
combined_tok['labels'] = [int(data['label']) if 'label' in data else -1]
combined_tok['seperate_ids'] = seperate_ids
combined_tok['extra'] = {
'dataset_format': self.dataset_format,
'end_with_eos': self.end_with_eos
}
return combined_tok
@dataclass
class AngleDataCollator:
"""
AngleDataCollator. It will be implicitly used in AnglE.fit().
It can only handle the tokenized data using AngleDataTokenizer.
:param tokenizer: PreTrainedTokenizerBase
:param padding: Union[bool, str, PaddingStrategy], padding strategy
:param max_length: Optional[int], max length
:param return_tensors: str
:param filter_duplicate: bool. Whether filter duplicate data
"""
tokenizer: PreTrainedTokenizerBase
padding: Union[bool, str, PaddingStrategy] = 'longest'
max_length: Optional[int] = None
return_tensors: str = "pt"
filter_duplicate: bool = True
def __call__(self, features: List[Dict], return_tensors: str = "pt") -> Dict[str, torch.Tensor]:
""" Collate function for AngleDataTokenizer.
:param features: List[Dict]. Tokenized data
:param return_tensors: str. Default "pt"
:return: Dict[str, torch.Tensor]. Collated data
"""
if return_tensors is None:
return_tensors = self.return_tensors
has_token_type_ids = "token_type_ids" in features[0]
end_with_eos = features[0]['extra']['end_with_eos']
new_features = []
duplicate_set = set()
for feature in features:
seperate_ids = feature['seperate_ids']
input_ids = feature['input_ids']
attention_mask = feature['attention_mask']
assert len(seperate_ids) == len(input_ids) == len(attention_mask)
has_token_type_ids = False
if "token_type_ids" in feature:
has_token_type_ids = True
token_type_ids = feature['token_type_ids']
assert len(token_type_ids) == len(input_ids)
max_seperate_id = max(seperate_ids)
prev_start_idx = 0
current_features = []
is_duplicate = False
for seperate_id in range(1, max_seperate_id + 1):
start_idx = seperate_ids.index(seperate_id)
new_feature = {}
new_input_ids = input_ids[prev_start_idx:start_idx]
if tuple(new_input_ids) in duplicate_set:
is_duplicate = True
if self.filter_duplicate:
break
duplicate_set.add(tuple(new_input_ids))
new_feature['input_ids'] = new_input_ids
new_feature['attention_mask'] = attention_mask[prev_start_idx:start_idx]
if has_token_type_ids:
new_feature['token_type_ids'] = token_type_ids[prev_start_idx:start_idx]
new_feature['labels'] = feature['labels']
current_features.append(new_feature)
prev_start_idx = start_idx
# last
new_feature = {}
new_input_ids = input_ids[prev_start_idx:]
if tuple(new_input_ids) in duplicate_set:
is_duplicate = True
duplicate_set.add(tuple(new_input_ids))
new_feature['input_ids'] = new_input_ids
new_feature['attention_mask'] = attention_mask[prev_start_idx:]
if has_token_type_ids:
new_feature['token_type_ids'] = token_type_ids[prev_start_idx:]
new_feature['labels'] = feature['labels']
current_features.append(new_feature)
if self.filter_duplicate and is_duplicate:
continue
new_features += current_features
# remove features
del features
if end_with_eos:
features = {}
features['input_ids'] = [feature['input_ids'] + [self.tokenizer.eos_token_id] for feature in new_features]
features = self.tokenizer.pad(
features,
padding=self.padding,
return_attention_mask=True,
return_tensors=return_tensors)
else:
features = self.tokenizer.pad(
{'input_ids': [feature['input_ids'] for feature in new_features]},
padding=self.padding,
max_length=self.max_length,
return_tensors=return_tensors,
)
features['attention_mask'] = self.tokenizer.pad(
{'input_ids': [feature['attention_mask'] for feature in new_features]},
padding=self.padding,
max_length=self.max_length,
return_tensors=return_tensors,
)['input_ids']
if has_token_type_ids:
features['token_type_ids'] = self.tokenizer.pad(
{'input_ids': [feature['token_type_ids'] for feature in new_features]},
padding=self.padding,
max_length=self.max_length,
return_tensors=return_tensors,
)['input_ids']
features['labels'] = torch.Tensor([feature['labels'] for feature in new_features])
return features
class Pooler:
"""
Using Pooler to obtain sentence embeddings.
:param model: PreTrainedModel
:param pooling_strategy: Optional[str]. Currently support [`cls`, `last`, `avg`, `cls_avg`, `max`]. Default None.
:param padding_strategy: Optional[str]. `left` or `right`. Default None.
:param is_llm: bool. Default False
"""
def __init__(self,
model: PreTrainedModel,
pooling_strategy: Optional[Union[int, str]] = None,
padding_strategy: Optional[str] = None):
self.model = model
self.pooling_strategy = pooling_strategy
self.padding_strategy = padding_strategy
def __call__(self,
inputs: Dict,
layer_index: int = -1,
embedding_start: Optional[int] = None,
embedding_size: Optional[int] = None,
return_all_layer_outputs: bool = False,
pooling_strategy: Optional[Union[int, str]] = None,) -> torch.Tensor:
""" Get sentence embeddings.
:param inputs: Dict. Model inputs.
:param layer_index: Optional[int]. Get embeddings from specific layer.
:param embedding_start: Optional[int]. Start index of embeddings.
:param embedding_size: int. Set embedding size for sentence embeddings.
:param return_all_layer_outputs: bool. Return all layer outputs or not. Default False.
:param pooling_strategy: Optional[str].
Currently support [`cls`, `last`, `avg`, `cls_avg`, `max`]. Default None.
"""
all_layer_outputs = self.model(output_hidden_states=True, return_dict=True, **inputs).hidden_states
if return_all_layer_outputs:
return all_layer_outputs
outputs = all_layer_outputs[layer_index]
outputs = get_pooling(outputs, inputs,
pooling_strategy or self.pooling_strategy,
padding_strategy=self.padding_strategy)
n_dim = len(outputs.shape)
if embedding_start is not None:
if n_dim == 2:
outputs = outputs[:, embedding_start:]
elif n_dim == 3:
outputs = outputs[:, :, embedding_start:]
else:
raise ValueError(f'Unsupported output shape: {outputs.shape}')
if embedding_size is not None:
# topk embedding size
if n_dim == 2:
outputs = outputs[:, :embedding_size]
elif n_dim == 3:
outputs = outputs[:, :, :embedding_size]
else:
raise ValueError(f'Unsupported output shape: {outputs.shape}')
return outputs
class AngleTrainer(Trainer):
"""
Custom Huggingface Trainer for AnglE.
:param pooler: Pooler. Required
:param loss_kwargs: Optional[Dict]. Default None.
:param dataset_format: str. Default DatasetFormats.A
:param teacher_name_or_path: Optional[str]. For distribution alignment.
:param **kwargs: other parameters of Trainer.
"""
def __init__(self,
pooler: Pooler,
loss_kwargs: Optional[Dict] = None,
dataset_format: str = DatasetFormats.A,
teacher_name_or_path: Optional[str] = None,
teacher_pooling_strategy: str = 'cls',
**kwargs):
super().__init__(**kwargs)
self.pooler = pooler
if loss_kwargs is None:
loss_kwargs = {}
self.loss_fct = AngleLoss(dataset_format=dataset_format, **loss_kwargs)
self.teacher_name_or_path = teacher_name_or_path
self.teacher_pooling_strategy = teacher_pooling_strategy
if teacher_name_or_path is not None:
logger.info('Teacher detected! '
'please ensure the teacher has the same tokenizer as the backbone model!')
assert not check_llm(teacher_name_or_path), ('Currently not support LLMs alignment,'
f' teacher={teacher_name_or_path}')
teacher_backbone = AutoModel.from_pretrained(
teacher_name_or_path,
trust_remote_code=True,
torch_dtype=self.pooler.model.dtype).to(self.pooler.model.device)
self.teacher_pooler = Pooler(
teacher_backbone,
pooling_strategy=self.teacher_pooling_strategy,
padding_strategy=self.pooler.padding_strategy)
logger.info(f'Train with teacher={teacher_name_or_path}')
def distillation_loss(self,
inputs: torch.Tensor,
targets: torch.Tensor,
mse_weight: float = 1.0,
kl_temperature: float = 1.0) -> torch.Tensor:
""" Compute distillation loss.
:param inputs: torch.Tensor. Input tensor.
:param targets: torch.Tensor. Target tensor.
:param mse_weight: float. MSE weight. Default 1.0.
:param kl_temperature: float. KL temperature. Default 1.0.
:return: torch.Tensor. Distillation loss.
"""
loss = 0.
if mse_weight > 0:
loss += mse_weight * nn.MSELoss()(inputs, targets)
if kl_temperature > 0:
loss += nn.KLDivLoss(reduction='batchmean')(
F.log_softmax(inputs / kl_temperature, dim=-1),
F.softmax(targets / kl_temperature, dim=-1)
) * kl_temperature
return loss
def compute_loss(self, model, inputs, return_outputs=False):
""" Compute loss for AnglE.
:param model: Huggingface model.
:param inputs: Dict. Model inputs.
:param return_outputs: bool. Return outputs or not. Default False.
:return: torch.Tensor. Loss.
"""
labels = inputs.pop("labels", None)
if self.teacher_name_or_path is not None:
all_outputs = self.pooler(inputs, layer_index=-1, return_all_layer_outputs=True)[-1]
outputs = get_pooling(all_outputs, inputs,
self.pooler.pooling_strategy,
self.pooler.padding_strategy)
loss = self.loss_fct(labels, outputs)
with torch.no_grad():
self.teacher_pooler.model = self.teacher_pooler.model.to(self.pooler.model.device)
align_outputs = self.teacher_pooler(inputs)
alignment_loss = self.distillation_loss(
all_outputs if self.teacher_pooling_strategy == 'all' else outputs,
align_outputs,
mse_weight=0.0,
kl_temperature=1.0)
loss += alignment_loss
else:
outputs = self.pooler(inputs)
loss = self.loss_fct(labels, outputs)
return (loss, outputs) if return_outputs else loss
class AngleESETrainer(AngleTrainer):
"""
Custom Huggingface Trainer for AnglE Espresso.
:param pooler: Pooler. Required
:param loss_kwargs: Optional[Dict]. Default None.
:param dataset_format: str. Default DatasetFormats.A
:param teacher_name_or_path: Optional[str]. For distribution alignment.
:param **kwargs: other parameters of Trainer.
"""
def __init__(self,
pooler: Pooler,
loss_kwargs: Optional[Dict] = None,
dataset_format: str = DatasetFormats.A,
teacher_name_or_path: Optional[str] = None,
ese_kl_temperature: float = 1.0,
ese_compression_size: int = 128,
apply_ese_pca: bool = True,
**kwargs):
super().__init__(pooler=pooler,
loss_kwargs=loss_kwargs,
dataset_format=dataset_format,
teacher_name_or_path=teacher_name_or_path,
**kwargs)
self.ese_kl_temperature = ese_kl_temperature
self.ese_compression_size = ese_compression_size
self.apply_ese_pca = apply_ese_pca
self.n_layers = self.pooler.model.config.num_hidden_layers
logger.info('Train with ☕️ Espresso!')
@torch.no_grad()
def pca_compress(self, m: torch.Tensor, k: int) -> torch.Tensor:
""" Get topk feature via PCA.
:param m: torch.Tensor. Input tensor.
:param k: int. Top-k feature size.
:return: torch.Tensor. Top-k feature.
"""
A = F.softmax(m.T @ m / m.shape[-1]**0.5, dim=-1)
u, s, _ = torch.svd_lowrank(A, q=k)
# top-k principal components
topk_deps = u @ torch.diag(s)
return m @ topk_deps
def compute_student_loss(self,
inputs: Dict,
all_layer_outputs: torch.Tensor,
labels: torch.Tensor,
pooling_strategy: str,
padding_strategy: str) -> torch.Tensor:
loss = 0.
compression_loss = 0.
for i in range(self.n_layers - 1):
division = (1. + math.log(1 + i))
all_student_outputs = all_layer_outputs[i]
student_outputs = get_pooling(all_student_outputs,
inputs,
pooling_strategy,
padding_strategy)
slimmed_outputs = student_outputs[:, :self.ese_compression_size]
loss += self.loss_fct(labels, slimmed_outputs) / division
if self.apply_ese_pca:
compression_loss += self.distillation_loss(
slimmed_outputs,
self.pca_compress(student_outputs, self.ese_compression_size),
kl_temperature=self.ese_kl_temperature
) / division
return (loss + compression_loss) / (self.n_layers - 1)
def compute_loss(self, model, inputs, return_outputs=False):
""" Compute loss for Espresso.
:param model: Huggingface model.
:param inputs: Dict. Model inputs.
:param return_outputs: bool. Return outputs or not. Default False.
:return: torch.Tensor. Loss.
"""
labels = inputs.pop("labels", None)
# layer
all_layer_outputs = self.pooler(inputs, layer_index=-1, return_all_layer_outputs=True)
all_teacher_outputs = all_layer_outputs[-1]
teacher_outputs = get_pooling(all_teacher_outputs, inputs,
self.pooler.pooling_strategy,
self.pooler.padding_strategy)
loss = self.loss_fct(labels, teacher_outputs)
slimmed_outputs = teacher_outputs[:, :self.ese_compression_size]
loss += self.loss_fct(labels, slimmed_outputs)
if self.apply_ese_pca:
loss += self.distillation_loss(
slimmed_outputs,
self.pca_compress(teacher_outputs, self.ese_compression_size),
kl_temperature=self.ese_kl_temperature
)
# student loss
loss += self.compute_student_loss(
inputs,
all_layer_outputs,
labels,
self.pooler.pooling_strategy,
self.pooler.padding_strategy,
)
# alignment loss
if self.teacher_name_or_path is not None:
with torch.no_grad():
self.teacher_pooler.model = self.teacher_pooler.model.to(self.pooler.model.device)
align_outputs = self.teacher_pooler(inputs)
alignment_loss = self.distillation_loss(
all_teacher_outputs if self.teacher_pooling_strategy == 'all' else teacher_outputs,
align_outputs,
mse_weight=0.0,
kl_temperature=1.0
)
loss += alignment_loss
return (loss, teacher_outputs) if return_outputs else loss
class AngleLoss:
"""
Configure AngleLoss.
:param cosine_w: float. weight for cosine_loss. Default 1.0
:param ibn_w: float. weight for contrastive loss. Default 1.0
:param angle_w: float. weight for angle loss. Default 1.0
:param cosine_tau: float. tau for cosine loss. Default 20.0
:param ibn_tau: float. tau for contrastive loss. Default 20.0
:param angle_tau: float. tau for angle loss. Default 20.0
:param angle_pooling_strategy: str. pooling strategy for angle loss. Default'sum'.
:param dataset_format: Optional[str]. Default None.
"""
def __init__(self,
cosine_w: float = 1.0,
ibn_w: float = 1.0,
angle_w: float = 1.0,
cosine_tau: float = 20.0,
ibn_tau: float = 20.0,
angle_tau: float = 20.0,
angle_pooling_strategy: str = 'sum',
dataset_format: Optional[str] = None,
**kwargs):
if 'w1' in kwargs or 'w2' in kwargs or 'w3' in kwargs:
assert ('w1, w2, and w3 has been renamed to cosine_w, ibn_w, and angle_w, respecitvely.'
'Please use new names instead.')
self.cosine_w = cosine_w
self.ibn_w = ibn_w
self.angle_w = angle_w
self.cosine_tau = cosine_tau
self.ibn_tau = ibn_tau
self.angle_tau = angle_tau
self.angle_pooling_strategy = angle_pooling_strategy
self.dataset_format = dataset_format
def __call__(self,