Skip to content

Commit 158d9ac

Browse files
committed
removed protobuf + transformers 5.x
1 parent 732604c commit 158d9ac

10 files changed

Lines changed: 1069 additions & 340 deletions

File tree

.github/workflows/ci.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ jobs:
88
runs-on: ubuntu-latest
99
strategy:
1010
matrix:
11-
python-version: [3.8, 3.9]
11+
python-version: [3.8, 3.9, 3.10]
1212

1313
steps:
1414
- uses: actions/checkout@v2

comet/encoders/base.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,18 @@ def from_pretrained(cls, pretrained_model: str):
8080
"""
8181
raise NotImplementedError
8282

83+
@abc.abstractmethod
84+
def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: List[int]) -> List[int]:
85+
"""Concatenate ids from two sequences.
86+
87+
This ensures compatibility with Transformers 4.x and 5.x, as the
88+
`build_inputs_with_special_tokens method` has been removed from `PreTrainedTokenizerBase`.
89+
90+
Returns:
91+
List[int]: an encoded sequence.
92+
"""
93+
pass
94+
8395
def freeze(self) -> None:
8496
"""Frezees the entire encoder."""
8597
for param in self.parameters():
@@ -304,7 +316,7 @@ def concat_sequences(
304316
torch.zeros(len(new_sequence[1:-1]) + 2, dtype=torch.int)
305317
)
306318
for j in range(1, len(inputs)):
307-
new_sequence = self.tokenizer.build_inputs_with_special_tokens(
319+
new_sequence = self.build_inputs_with_special_tokens(
308320
new_sequence[1:-1], concat_input_ids[j][i][1:-1]
309321
)
310322
if sum(lengths) > self.max_positions - special_tokens:

comet/encoders/bert.py

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
==============
1818
Pretrained BERT encoder from Hugging Face.
1919
"""
20-
from typing import Dict, Optional
20+
from typing import Dict, List, Optional
2121

2222
import torch
2323
from transformers import BertConfig, BertModel, BertTokenizerFast
@@ -115,6 +115,23 @@ def freeze_embeddings(self) -> None:
115115
for param in self.model.embeddings.parameters():
116116
param.requires_grad = False
117117

118+
def build_inputs_with_special_tokens(
119+
self, token_ids_0: List[int], token_ids_1: List[int]
120+
) -> List[int]:
121+
"""Concatenate ids from two sequences.
122+
123+
Returns:
124+
List[int]: an encoded sequence.
125+
"""
126+
return (
127+
[self.tokenizer.cls_token_id]
128+
+ token_ids_0
129+
+ [self.tokenizer.sep_token_id]
130+
+ token_ids_1
131+
+ [self.tokenizer.sep_token_id]
132+
)
133+
134+
118135
def layerwise_lr(self, lr: float, decay: float):
119136
"""Calculates the learning rate for each layer by applying a small decay.
120137
@@ -168,15 +185,23 @@ def forward(
168185
Dict[str, torch.Tensor]: dictionary with 'sentemb', 'wordemb', 'all_layers'
169186
and 'attention_mask'.
170187
"""
171-
last_hidden_states, pooler_output, all_layers = self.model(
188+
output = self.model(
172189
input_ids=input_ids,
173190
token_type_ids=token_type_ids,
174191
attention_mask=attention_mask,
175192
output_hidden_states=True,
176193
return_dict=False,
177194
)
195+
196+
if len(output) == 2:
197+
last_hidden_states, all_layers = output
198+
sentemb = last_hidden_states[:, 0, :]
199+
else:
200+
last_hidden_states, pooler_output, all_layers = output
201+
sentemb = pooler_output if pooler_output is not None else last_hidden_states[:, 0, :]
202+
178203
return {
179-
"sentemb": pooler_output,
204+
"sentemb": sentemb,
180205
"wordemb": last_hidden_states,
181206
"all_layers": all_layers,
182207
"attention_mask": attention_mask,

comet/encoders/rembert.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
Pretrained RemBERT encoder from Google. This encoder is similar to BERT but uses
1919
sentencepiece like XLMR.
2020
"""
21+
from typing import List
22+
2123
from transformers import RemBertConfig, RemBertModel, RemBertTokenizerFast
2224

2325
from comet.encoders.xlmr import Encoder, XLMREncoder
@@ -63,6 +65,22 @@ def size_separator(self):
6365
def uses_token_type_ids(self):
6466
return True
6567

68+
def build_inputs_with_special_tokens(
69+
self, token_ids_0: List[int], token_ids_1: List[int]
70+
) -> List[int]:
71+
"""Concatenate ids from two sequences.
72+
73+
Returns:
74+
List[int]: an encoded sequence.
75+
"""
76+
return (
77+
[self.tokenizer.cls_token_id]
78+
+ token_ids_0
79+
+ [self.tokenizer.sep_token_id]
80+
+ token_ids_1
81+
+ [self.tokenizer.sep_token_id]
82+
)
83+
6684
@classmethod
6785
def from_pretrained(
6886
cls,

comet/encoders/xlmr.py

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
==============
1818
Pretrained XLM-RoBERTa encoder from Hugging Face.
1919
"""
20-
from typing import Dict
20+
from typing import Dict, List
2121

2222
import torch
2323
from transformers import XLMRobertaConfig, XLMRobertaModel, XLMRobertaTokenizerFast
@@ -69,6 +69,22 @@ def size_separator(self):
6969
def uses_token_type_ids(self):
7070
return False
7171

72+
def build_inputs_with_special_tokens(
73+
self, token_ids_0: List[int], token_ids_1: List[int]
74+
) -> List[int]:
75+
"""Concatenate ids from two sequences.
76+
77+
Returns:
78+
List[int]: an encoded sequence.
79+
"""
80+
return (
81+
[self.tokenizer.cls_token_id]
82+
+ token_ids_0
83+
+ [self.tokenizer.sep_token_id] * 2
84+
+ token_ids_1
85+
+ [self.tokenizer.sep_token_id]
86+
)
87+
7288
@classmethod
7389
def from_pretrained(
7490
cls,
@@ -92,12 +108,18 @@ def from_pretrained(
92108
def forward(
93109
self, input_ids: torch.Tensor, attention_mask: torch.Tensor, **kwargs
94110
) -> Dict[str, torch.Tensor]:
95-
last_hidden_states, _, all_layers = self.model(
111+
output = self.model(
96112
input_ids=input_ids,
97113
attention_mask=attention_mask,
98114
output_hidden_states=True,
99115
return_dict=False,
100116
)
117+
118+
if len(output) == 2:
119+
last_hidden_states, all_layers = output
120+
else:
121+
last_hidden_states, _, all_layers = output
122+
101123
return {
102124
"sentemb": last_hidden_states[:, 0, :],
103125
"wordemb": last_hidden_states,

comet/models/predict_writer.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -97,14 +97,18 @@ def flatten_predictions(predictions):
9797
files = sorted(os.listdir(self.output_dir))
9898
pred = flatten_predictions(
9999
[
100-
flatten_predictions(torch.load(os.path.join(self.output_dir, f)))
100+
flatten_predictions(
101+
torch.load(os.path.join(self.output_dir, f), weights_only=False)
102+
)
101103
for f in files
102104
if "pred" in f
103105
]
104106
)
105107
indices = flatten(
106108
[
107-
flatten(torch.load(os.path.join(self.output_dir, f))[0])
109+
flatten(
110+
torch.load(os.path.join(self.output_dir, f), weights_only=False)[0]
111+
)
108112
for f in files
109113
if "batch_indices" in f
110114
]

0 commit comments

Comments
 (0)