Spaces:
Runtime error
Runtime error
Add criterions folder
Browse files- criterions/__init__.py +2 -0
- criterions/label_smoothed_cross_entropy.py +343 -0
- criterions/scst_loss.py +280 -0
criterions/__init__.py
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
from .scst_loss import ScstRewardCriterion
|
2 |
+
from .label_smoothed_cross_entropy import AjustLabelSmoothedCrossEntropyCriterion
|
criterions/label_smoothed_cross_entropy.py
ADDED
@@ -0,0 +1,343 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
2 |
+
#
|
3 |
+
# This source code is licensed under the MIT license found in the
|
4 |
+
# LICENSE file in the root directory of this source tree.
|
5 |
+
|
6 |
+
import math
|
7 |
+
from dataclasses import dataclass, field
|
8 |
+
from typing import Optional
|
9 |
+
|
10 |
+
import torch
|
11 |
+
import torch.nn.functional as F
|
12 |
+
import numpy as np
|
13 |
+
from fairseq import metrics, utils
|
14 |
+
from fairseq.criterions import FairseqCriterion, register_criterion
|
15 |
+
from fairseq.dataclass import FairseqDataclass
|
16 |
+
from omegaconf import II
|
17 |
+
|
18 |
+
|
19 |
+
@dataclass
|
20 |
+
class AjustLabelSmoothedCrossEntropyCriterionConfig(FairseqDataclass):
|
21 |
+
label_smoothing: float = field(
|
22 |
+
default=0.0,
|
23 |
+
metadata={"help": "epsilon for label smoothing, 0 means no label smoothing"},
|
24 |
+
)
|
25 |
+
report_accuracy: bool = field(
|
26 |
+
default=False,
|
27 |
+
metadata={"help": "report accuracy metric"},
|
28 |
+
)
|
29 |
+
ignore_prefix_size: int = field(
|
30 |
+
default=0,
|
31 |
+
metadata={"help": "Ignore first N tokens"},
|
32 |
+
)
|
33 |
+
ignore_eos: bool = field(
|
34 |
+
default=False,
|
35 |
+
metadata={"help": "Ignore eos token"},
|
36 |
+
)
|
37 |
+
sentence_avg: bool = II("optimization.sentence_avg")
|
38 |
+
drop_worst_ratio: float = field(
|
39 |
+
default=0.0,
|
40 |
+
metadata={"help": "ratio for discarding bad samples"},
|
41 |
+
)
|
42 |
+
drop_worst_after: int = field(
|
43 |
+
default=0,
|
44 |
+
metadata={"help": "steps for discarding bad samples"},
|
45 |
+
)
|
46 |
+
use_rdrop: bool = field(
|
47 |
+
default=False, metadata={"help": "use R-Drop"}
|
48 |
+
)
|
49 |
+
reg_alpha: float = field(
|
50 |
+
default=1.0, metadata={"help": "weight for R-Drop"}
|
51 |
+
)
|
52 |
+
sample_patch_num: int = field(
|
53 |
+
default=196, metadata={"help": "sample patchs for v1"}
|
54 |
+
)
|
55 |
+
constraint_range: Optional[str] = field(
|
56 |
+
default=None,
|
57 |
+
metadata={"help": "constraint range"}
|
58 |
+
)
|
59 |
+
|
60 |
+
|
61 |
+
def construct_rdrop_sample(x):
|
62 |
+
if isinstance(x, dict):
|
63 |
+
for key in x:
|
64 |
+
x[key] = construct_rdrop_sample(x[key])
|
65 |
+
return x
|
66 |
+
elif isinstance(x, torch.Tensor):
|
67 |
+
return x.repeat(2, *([1] * (x.dim()-1)))
|
68 |
+
elif isinstance(x, int):
|
69 |
+
return x * 2
|
70 |
+
elif isinstance(x, np.ndarray):
|
71 |
+
return x.repeat(2)
|
72 |
+
else:
|
73 |
+
raise NotImplementedError
|
74 |
+
|
75 |
+
|
76 |
+
def kl_loss(p, q):
|
77 |
+
p_loss = F.kl_div(p, torch.exp(q), reduction='sum')
|
78 |
+
q_loss = F.kl_div(q, torch.exp(p), reduction='sum')
|
79 |
+
loss = (p_loss + q_loss) / 2
|
80 |
+
return loss
|
81 |
+
|
82 |
+
|
83 |
+
def label_smoothed_nll_loss(
|
84 |
+
lprobs, target, epsilon, update_num, reduce=True,
|
85 |
+
drop_worst_ratio=0.0, drop_worst_after=0, use_rdrop=False, reg_alpha=1.0,
|
86 |
+
constraint_masks=None, constraint_start=None, constraint_end=None
|
87 |
+
):
|
88 |
+
if target.dim() == lprobs.dim() - 1:
|
89 |
+
target = target.unsqueeze(-1)
|
90 |
+
nll_loss = -lprobs.gather(dim=-1, index=target).squeeze(-1)
|
91 |
+
if constraint_masks is not None:
|
92 |
+
smooth_loss = -lprobs.masked_fill(~constraint_masks, 0).sum(dim=-1, keepdim=True).squeeze(-1)
|
93 |
+
eps_i = epsilon / (constraint_masks.sum(1) - 1 + 1e-6)
|
94 |
+
elif constraint_start is not None and constraint_end is not None:
|
95 |
+
constraint_range = [0, 1, 2, 3] + list(range(constraint_start, constraint_end))
|
96 |
+
smooth_loss = -lprobs[:, constraint_range].sum(dim=-1, keepdim=True).squeeze(-1)
|
97 |
+
eps_i = epsilon / (len(constraint_range) - 1 + 1e-6)
|
98 |
+
else:
|
99 |
+
smooth_loss = -lprobs.sum(dim=-1, keepdim=True).squeeze(-1)
|
100 |
+
eps_i = epsilon / (lprobs.size(-1) - 1)
|
101 |
+
loss = (1.0 - epsilon - eps_i) * nll_loss + eps_i * smooth_loss
|
102 |
+
if drop_worst_ratio > 0 and update_num > drop_worst_after:
|
103 |
+
if use_rdrop:
|
104 |
+
true_batch_size = loss.size(0) // 2
|
105 |
+
_, indices = torch.topk(loss[:true_batch_size], k=int(true_batch_size * (1 - drop_worst_ratio)), largest=False)
|
106 |
+
loss = torch.cat([loss[indices], loss[indices+true_batch_size]])
|
107 |
+
nll_loss = torch.cat([nll_loss[indices], nll_loss[indices+true_batch_size]])
|
108 |
+
lprobs = torch.cat([lprobs[indices], lprobs[indices+true_batch_size]])
|
109 |
+
else:
|
110 |
+
loss, indices = torch.topk(loss, k=int(loss.shape[0] * (1 - drop_worst_ratio)), largest=False)
|
111 |
+
nll_loss = nll_loss[indices]
|
112 |
+
lprobs = lprobs[indices]
|
113 |
+
|
114 |
+
ntokens = loss.numel()
|
115 |
+
nll_loss = nll_loss.sum()
|
116 |
+
loss = loss.sum()
|
117 |
+
if use_rdrop:
|
118 |
+
true_batch_size = lprobs.size(0) // 2
|
119 |
+
p = lprobs[:true_batch_size]
|
120 |
+
q = lprobs[true_batch_size:]
|
121 |
+
if constraint_start is not None and constraint_end is not None:
|
122 |
+
constraint_range = [0, 1, 2, 3] + list(range(constraint_start, constraint_end))
|
123 |
+
p = p[:, constraint_range]
|
124 |
+
q = q[:, constraint_range]
|
125 |
+
loss += kl_loss(p, q) * reg_alpha
|
126 |
+
|
127 |
+
return loss, nll_loss, ntokens
|
128 |
+
|
129 |
+
|
130 |
+
@register_criterion(
|
131 |
+
"ajust_label_smoothed_cross_entropy", dataclass=AjustLabelSmoothedCrossEntropyCriterionConfig
|
132 |
+
)
|
133 |
+
class AjustLabelSmoothedCrossEntropyCriterion(FairseqCriterion):
|
134 |
+
def __init__(
|
135 |
+
self,
|
136 |
+
task,
|
137 |
+
sentence_avg,
|
138 |
+
label_smoothing,
|
139 |
+
ignore_prefix_size=0,
|
140 |
+
ignore_eos=False,
|
141 |
+
report_accuracy=False,
|
142 |
+
drop_worst_ratio=0,
|
143 |
+
drop_worst_after=0,
|
144 |
+
use_rdrop=False,
|
145 |
+
reg_alpha=1.0,
|
146 |
+
sample_patch_num=196,
|
147 |
+
constraint_range=None
|
148 |
+
):
|
149 |
+
super().__init__(task)
|
150 |
+
self.sentence_avg = sentence_avg
|
151 |
+
self.eps = label_smoothing
|
152 |
+
self.ignore_prefix_size = ignore_prefix_size
|
153 |
+
self.ignore_eos = ignore_eos
|
154 |
+
self.report_accuracy = report_accuracy
|
155 |
+
self.drop_worst_ratio = drop_worst_ratio
|
156 |
+
self.drop_worst_after = drop_worst_after
|
157 |
+
self.use_rdrop = use_rdrop
|
158 |
+
self.reg_alpha = reg_alpha
|
159 |
+
self.sample_patch_num = sample_patch_num
|
160 |
+
|
161 |
+
self.constraint_start = None
|
162 |
+
self.constraint_end = None
|
163 |
+
if constraint_range is not None:
|
164 |
+
constraint_start, constraint_end = constraint_range.split(',')
|
165 |
+
self.constraint_start = int(constraint_start)
|
166 |
+
self.constraint_end = int(constraint_end)
|
167 |
+
|
168 |
+
def forward(self, model, sample, update_num=0, reduce=True):
|
169 |
+
"""Compute the loss for the given sample.
|
170 |
+
|
171 |
+
Returns a tuple with three elements:
|
172 |
+
1) the loss
|
173 |
+
2) the sample size, which is used as the denominator for the gradient
|
174 |
+
3) logging outputs to display while training
|
175 |
+
"""
|
176 |
+
if isinstance(sample, list):
|
177 |
+
if self.sample_patch_num > 0:
|
178 |
+
sample[0]['net_input']['sample_patch_num'] = self.sample_patch_num
|
179 |
+
loss_v1, sample_size_v1, logging_output_v1 = self.forward(model, sample[0], update_num, reduce)
|
180 |
+
loss_v2, sample_size_v2, logging_output_v2 = self.forward(model, sample[1], update_num, reduce)
|
181 |
+
loss = loss_v1 / sample_size_v1 + loss_v2 / sample_size_v2
|
182 |
+
sample_size = 1
|
183 |
+
logging_output = {
|
184 |
+
"loss": loss.data,
|
185 |
+
"loss_v1": loss_v1.data,
|
186 |
+
"loss_v2": loss_v2.data,
|
187 |
+
"nll_loss": logging_output_v1["nll_loss"].data / sample_size_v1 + logging_output_v2["nll_loss"].data / sample_size_v2,
|
188 |
+
"ntokens": logging_output_v1["ntokens"] + logging_output_v2["ntokens"],
|
189 |
+
"nsentences": logging_output_v1["nsentences"] + logging_output_v2["nsentences"],
|
190 |
+
"sample_size": 1,
|
191 |
+
"sample_size_v1": sample_size_v1,
|
192 |
+
"sample_size_v2": sample_size_v2,
|
193 |
+
}
|
194 |
+
return loss, sample_size, logging_output
|
195 |
+
|
196 |
+
if self.use_rdrop:
|
197 |
+
construct_rdrop_sample(sample)
|
198 |
+
|
199 |
+
net_output = model(**sample["net_input"])
|
200 |
+
loss, nll_loss, ntokens = self.compute_loss(model, net_output, sample, update_num, reduce=reduce)
|
201 |
+
sample_size = (
|
202 |
+
sample["target"].size(0) if self.sentence_avg else ntokens
|
203 |
+
)
|
204 |
+
logging_output = {
|
205 |
+
"loss": loss.data,
|
206 |
+
"nll_loss": nll_loss.data,
|
207 |
+
"ntokens": sample["ntokens"],
|
208 |
+
"nsentences": sample["nsentences"],
|
209 |
+
"sample_size": sample_size,
|
210 |
+
}
|
211 |
+
if self.report_accuracy:
|
212 |
+
n_correct, total = self.compute_accuracy(model, net_output, sample)
|
213 |
+
logging_output["n_correct"] = utils.item(n_correct.data)
|
214 |
+
logging_output["total"] = utils.item(total.data)
|
215 |
+
return loss, sample_size, logging_output
|
216 |
+
|
217 |
+
def get_lprobs_and_target(self, model, net_output, sample):
|
218 |
+
conf = sample['conf'][:, None, None] if 'conf' in sample and sample['conf'] is not None else 1
|
219 |
+
constraint_masks = None
|
220 |
+
if "constraint_masks" in sample and sample["constraint_masks"] is not None:
|
221 |
+
constraint_masks = sample["constraint_masks"]
|
222 |
+
net_output[0].masked_fill_(~constraint_masks, -math.inf)
|
223 |
+
if self.constraint_start is not None and self.constraint_end is not None:
|
224 |
+
net_output[0][:, :, 4:self.constraint_start] = -math.inf
|
225 |
+
net_output[0][:, :, self.constraint_end:] = -math.inf
|
226 |
+
lprobs = model.get_normalized_probs(net_output, log_probs=True) * conf
|
227 |
+
target = model.get_targets(sample, net_output)
|
228 |
+
if self.ignore_prefix_size > 0:
|
229 |
+
lprobs = lprobs[:, self.ignore_prefix_size :, :].contiguous()
|
230 |
+
target = target[:, self.ignore_prefix_size :].contiguous()
|
231 |
+
if constraint_masks is not None:
|
232 |
+
constraint_masks = constraint_masks[:, self.ignore_prefix_size :, :].contiguous()
|
233 |
+
if self.ignore_eos:
|
234 |
+
bsz, seq_len, embed_dim = lprobs.size()
|
235 |
+
eos_indices = target.eq(self.task.tgt_dict.eos())
|
236 |
+
lprobs = lprobs[~eos_indices].reshape(bsz, seq_len-1, embed_dim)
|
237 |
+
target = target[~eos_indices].reshape(bsz, seq_len-1)
|
238 |
+
if constraint_masks is not None:
|
239 |
+
constraint_masks = constraint_masks[~eos_indices].reshape(bsz, seq_len-1, embed_dim)
|
240 |
+
if constraint_masks is not None:
|
241 |
+
constraint_masks = constraint_masks.view(-1, constraint_masks.size(-1))
|
242 |
+
return lprobs.view(-1, lprobs.size(-1)), target.view(-1), constraint_masks
|
243 |
+
|
244 |
+
def compute_loss(self, model, net_output, sample, update_num, reduce=True):
|
245 |
+
lprobs, target, constraint_masks = self.get_lprobs_and_target(model, net_output, sample)
|
246 |
+
if constraint_masks is not None:
|
247 |
+
constraint_masks = constraint_masks[target != self.padding_idx]
|
248 |
+
lprobs = lprobs[target != self.padding_idx]
|
249 |
+
target = target[target != self.padding_idx]
|
250 |
+
loss, nll_loss, ntokens = label_smoothed_nll_loss(
|
251 |
+
lprobs,
|
252 |
+
target,
|
253 |
+
self.eps,
|
254 |
+
update_num,
|
255 |
+
reduce=reduce,
|
256 |
+
drop_worst_ratio=self.drop_worst_ratio,
|
257 |
+
drop_worst_after=self.drop_worst_after,
|
258 |
+
use_rdrop=self.use_rdrop,
|
259 |
+
reg_alpha=self.reg_alpha,
|
260 |
+
constraint_masks=constraint_masks,
|
261 |
+
constraint_start=self.constraint_start,
|
262 |
+
constraint_end=self.constraint_end
|
263 |
+
)
|
264 |
+
return loss, nll_loss, ntokens
|
265 |
+
|
266 |
+
def compute_accuracy(self, model, net_output, sample):
|
267 |
+
lprobs, target = self.get_lprobs_and_target(model, net_output, sample)
|
268 |
+
mask = target.ne(self.padding_idx)
|
269 |
+
n_correct = torch.sum(
|
270 |
+
lprobs.argmax(1).masked_select(mask).eq(target.masked_select(mask))
|
271 |
+
)
|
272 |
+
total = torch.sum(mask)
|
273 |
+
return n_correct, total
|
274 |
+
|
275 |
+
@classmethod
|
276 |
+
def reduce_metrics(cls, logging_outputs) -> None:
|
277 |
+
"""Aggregate logging outputs from data parallel training."""
|
278 |
+
loss_sum = sum(log.get("loss", 0) for log in logging_outputs)
|
279 |
+
loss_sum_v1 = sum(log.get("loss_v1", 0) for log in logging_outputs)
|
280 |
+
loss_sum_v2 = sum(log.get("loss_v2", 0) for log in logging_outputs)
|
281 |
+
nll_loss_sum = sum(log.get("nll_loss", 0) for log in logging_outputs)
|
282 |
+
ntokens = sum(log.get("ntokens", 0) for log in logging_outputs)
|
283 |
+
nsentences = sum(log.get("nsentences", 0) for log in logging_outputs)
|
284 |
+
sample_size = sum(log.get("sample_size", 0) for log in logging_outputs)
|
285 |
+
sample_size_v1 = sum(log.get("sample_size_v1", 0) for log in logging_outputs)
|
286 |
+
sample_size_v2 = sum(log.get("sample_size_v2", 0) for log in logging_outputs)
|
287 |
+
|
288 |
+
metrics.log_scalar(
|
289 |
+
"loss", loss_sum / sample_size, sample_size, round=3
|
290 |
+
)
|
291 |
+
metrics.log_scalar(
|
292 |
+
"loss_v1", loss_sum_v1 / max(sample_size_v1, 1), max(sample_size_v1, 1), round=3
|
293 |
+
)
|
294 |
+
metrics.log_scalar(
|
295 |
+
"loss_v2", loss_sum_v2 / max(sample_size_v2, 1), max(sample_size_v2, 1), round=3
|
296 |
+
)
|
297 |
+
metrics.log_scalar(
|
298 |
+
"nll_loss", nll_loss_sum / sample_size, ntokens, round=3
|
299 |
+
)
|
300 |
+
metrics.log_derived(
|
301 |
+
"ppl", lambda meters: utils.get_perplexity(meters["nll_loss"].avg)
|
302 |
+
)
|
303 |
+
|
304 |
+
metrics.log_scalar(
|
305 |
+
"ntokens", ntokens, 1, round=3
|
306 |
+
)
|
307 |
+
metrics.log_scalar(
|
308 |
+
"nsentences", nsentences, 1, round=3
|
309 |
+
)
|
310 |
+
metrics.log_scalar(
|
311 |
+
"sample_size", sample_size, 1, round=3
|
312 |
+
)
|
313 |
+
metrics.log_scalar(
|
314 |
+
"sample_size_v1", sample_size_v1, 1, round=3
|
315 |
+
)
|
316 |
+
metrics.log_scalar(
|
317 |
+
"sample_size_v2", sample_size_v2, 1, round=3
|
318 |
+
)
|
319 |
+
|
320 |
+
total = utils.item(sum(log.get("total", 0) for log in logging_outputs))
|
321 |
+
if total > 0:
|
322 |
+
metrics.log_scalar("total", total)
|
323 |
+
n_correct = utils.item(
|
324 |
+
sum(log.get("n_correct", 0) for log in logging_outputs)
|
325 |
+
)
|
326 |
+
metrics.log_scalar("n_correct", n_correct)
|
327 |
+
metrics.log_derived(
|
328 |
+
"accuracy",
|
329 |
+
lambda meters: round(
|
330 |
+
meters["n_correct"].sum * 100.0 / meters["total"].sum, 3
|
331 |
+
)
|
332 |
+
if meters["total"].sum > 0
|
333 |
+
else float("nan"),
|
334 |
+
)
|
335 |
+
|
336 |
+
@staticmethod
|
337 |
+
def logging_outputs_can_be_summed() -> bool:
|
338 |
+
"""
|
339 |
+
Whether the logging outputs returned by `forward` can be summed
|
340 |
+
across workers prior to calling `reduce_metrics`. Setting this
|
341 |
+
to True will improves distributed training speed.
|
342 |
+
"""
|
343 |
+
return True
|
criterions/scst_loss.py
ADDED
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) Facebook, Inc. and its affiliates.
|
2 |
+
#
|
3 |
+
# This source code is licensed under the MIT license found in the
|
4 |
+
# LICENSE file in the root directory of this source tree.
|
5 |
+
|
6 |
+
import math
|
7 |
+
import string
|
8 |
+
from dataclasses import dataclass, field
|
9 |
+
from collections import OrderedDict
|
10 |
+
from typing import Optional
|
11 |
+
|
12 |
+
import torch
|
13 |
+
from fairseq import metrics, utils
|
14 |
+
from fairseq.criterions import FairseqCriterion, register_criterion
|
15 |
+
from fairseq.dataclass import FairseqDataclass
|
16 |
+
from omegaconf import II
|
17 |
+
|
18 |
+
from data import data_utils
|
19 |
+
from utils.cider.pyciderevalcap.ciderD.ciderD import CiderD
|
20 |
+
|
21 |
+
|
22 |
+
def scst_loss(lprobs, target, reward, ignore_index=None, reduce=True):
|
23 |
+
loss = -lprobs.gather(dim=-1, index=target.unsqueeze(-1)).squeeze() * reward.unsqueeze(-1)
|
24 |
+
if ignore_index is not None:
|
25 |
+
pad_mask = target.eq(ignore_index)
|
26 |
+
loss.masked_fill_(pad_mask, 0.0)
|
27 |
+
ntokens = (~pad_mask).sum()
|
28 |
+
else:
|
29 |
+
loss = loss.squeeze(-1)
|
30 |
+
ntokens = target.numel()
|
31 |
+
if reduce:
|
32 |
+
loss = loss.sum()
|
33 |
+
return loss, ntokens
|
34 |
+
|
35 |
+
@dataclass
|
36 |
+
class ScstRewardCriterionConfig(FairseqDataclass):
|
37 |
+
scst_cider_cached_tokens: str = field(
|
38 |
+
default="coco-train-words.p",
|
39 |
+
metadata={"help": "path to cached cPickle file used to calculate CIDEr scores"},
|
40 |
+
)
|
41 |
+
ignore_prefix_size: int = field(
|
42 |
+
default=0,
|
43 |
+
metadata={"help": "Ignore first N tokens"},
|
44 |
+
)
|
45 |
+
sentence_avg: bool = II("optimization.sentence_avg")
|
46 |
+
constraint_range: Optional[str] = field(
|
47 |
+
default=None,
|
48 |
+
metadata={"help": "constraint range"}
|
49 |
+
)
|
50 |
+
|
51 |
+
|
52 |
+
@register_criterion(
|
53 |
+
"scst_reward_criterion", dataclass=ScstRewardCriterionConfig
|
54 |
+
)
|
55 |
+
class ScstRewardCriterion(FairseqCriterion):
|
56 |
+
CIDER_REWARD_WEIGHT = 1
|
57 |
+
|
58 |
+
def __init__(
|
59 |
+
self,
|
60 |
+
task,
|
61 |
+
scst_cider_cached_tokens,
|
62 |
+
sentence_avg,
|
63 |
+
ignore_prefix_size=0,
|
64 |
+
constraint_range=None
|
65 |
+
):
|
66 |
+
super().__init__(task)
|
67 |
+
self.scst_cider_scorer = CiderD(df=scst_cider_cached_tokens)
|
68 |
+
self.sentence_avg = sentence_avg
|
69 |
+
self.ignore_prefix_size = ignore_prefix_size
|
70 |
+
self.transtab = str.maketrans({key: None for key in string.punctuation})
|
71 |
+
|
72 |
+
self.constraint_start = None
|
73 |
+
self.constraint_end = None
|
74 |
+
if constraint_range is not None:
|
75 |
+
constraint_start, constraint_end = constraint_range.split(',')
|
76 |
+
self.constraint_start = int(constraint_start)
|
77 |
+
self.constraint_end = int(constraint_end)
|
78 |
+
|
79 |
+
def forward(self, model, sample, reduce=True):
|
80 |
+
"""Compute the loss for the given sample.
|
81 |
+
|
82 |
+
Returns a tuple with three elements:
|
83 |
+
1) the loss
|
84 |
+
2) the sample size, which is used as the denominator for the gradient
|
85 |
+
3) logging outputs to display while training
|
86 |
+
"""
|
87 |
+
loss, score, ntokens, nsentences = self.compute_loss(model, sample, reduce=reduce)
|
88 |
+
|
89 |
+
sample_size = (
|
90 |
+
nsentences if self.sentence_avg else ntokens
|
91 |
+
)
|
92 |
+
logging_output = {
|
93 |
+
"loss": loss.data,
|
94 |
+
"score": score,
|
95 |
+
"ntokens": ntokens,
|
96 |
+
"nsentences": nsentences,
|
97 |
+
"sample_size": sample_size,
|
98 |
+
}
|
99 |
+
return loss, sample_size, logging_output
|
100 |
+
|
101 |
+
def _calculate_eval_scores(self, gen_res, gt_idx, gt_res):
|
102 |
+
'''
|
103 |
+
gen_res: generated captions, list of str
|
104 |
+
gt_idx: list of int, of the same length as gen_res
|
105 |
+
gt_res: ground truth captions, list of list of str.
|
106 |
+
gen_res[i] corresponds to gt_res[gt_idx[i]]
|
107 |
+
Each image can have multiple ground truth captions
|
108 |
+
'''
|
109 |
+
gen_res_size = len(gen_res)
|
110 |
+
|
111 |
+
res = OrderedDict()
|
112 |
+
for i in range(gen_res_size):
|
113 |
+
res[i] = [self._wrap_sentence(gen_res[i].strip().translate(self.transtab))]
|
114 |
+
|
115 |
+
gts = OrderedDict()
|
116 |
+
gt_res_ = [
|
117 |
+
[self._wrap_sentence(gt_res[i][j].strip().translate(self.transtab)) for j in range(len(gt_res[i]))]
|
118 |
+
for i in range(len(gt_res))
|
119 |
+
]
|
120 |
+
for i in range(gen_res_size):
|
121 |
+
gts[i] = gt_res_[gt_idx[i]]
|
122 |
+
|
123 |
+
res_ = [{'image_id':i, 'caption': res[i]} for i in range(len(res))]
|
124 |
+
_, batch_cider_scores = self.scst_cider_scorer.compute_score(gts, res_)
|
125 |
+
scores = self.CIDER_REWARD_WEIGHT * batch_cider_scores
|
126 |
+
return scores
|
127 |
+
|
128 |
+
@classmethod
|
129 |
+
def _wrap_sentence(self, s):
|
130 |
+
# ensure the sentence ends with <eos> token
|
131 |
+
# in order to keep consisitent with cider_cached_tokens
|
132 |
+
r = s.strip()
|
133 |
+
if r.endswith('.'):
|
134 |
+
r = r[:-1]
|
135 |
+
r += ' <eos>'
|
136 |
+
return r
|
137 |
+
|
138 |
+
def get_generator_out(self, model, sample):
|
139 |
+
def decode(toks):
|
140 |
+
hypo = toks.int().cpu()
|
141 |
+
hypo_str = self.task.tgt_dict.string(hypo)
|
142 |
+
hypo_str = self.task.bpe.decode(hypo_str).strip()
|
143 |
+
return hypo, hypo_str
|
144 |
+
|
145 |
+
model.eval()
|
146 |
+
with torch.no_grad():
|
147 |
+
self.task.scst_generator.model.eval()
|
148 |
+
gen_out = self.task.scst_generator.generate([model], sample)
|
149 |
+
|
150 |
+
gen_target = []
|
151 |
+
gen_res = []
|
152 |
+
gt_res = []
|
153 |
+
for i in range(len(gen_out)):
|
154 |
+
for j in range(len(gen_out[i])):
|
155 |
+
hypo, hypo_str = decode(gen_out[i][j]["tokens"])
|
156 |
+
gen_target.append(hypo)
|
157 |
+
gen_res.append(hypo_str)
|
158 |
+
gt_res.append(
|
159 |
+
decode(utils.strip_pad(sample["target"][i], self.padding_idx))[1].split('&&')
|
160 |
+
)
|
161 |
+
|
162 |
+
return gen_target, gen_res, gt_res
|
163 |
+
|
164 |
+
def get_reward_and_scores(self, gen_res, gt_res, device):
|
165 |
+
batch_size = len(gt_res)
|
166 |
+
gen_res_size = len(gen_res)
|
167 |
+
seq_per_img = gen_res_size // batch_size
|
168 |
+
|
169 |
+
gt_idx = [i // seq_per_img for i in range(gen_res_size)]
|
170 |
+
scores = self._calculate_eval_scores(gen_res, gt_idx, gt_res)
|
171 |
+
sc_ = scores.reshape(batch_size, seq_per_img)
|
172 |
+
baseline = (sc_.sum(1, keepdims=True) - sc_) / (sc_.shape[1] - 1)
|
173 |
+
# sample - baseline
|
174 |
+
reward = scores.reshape(batch_size, seq_per_img)
|
175 |
+
reward = reward - baseline
|
176 |
+
reward = reward.reshape(gen_res_size)
|
177 |
+
reward = torch.as_tensor(reward, device=device, dtype=torch.float64)
|
178 |
+
|
179 |
+
return reward, scores
|
180 |
+
|
181 |
+
def get_net_output(self, model, sample, gen_target):
|
182 |
+
def merge(sample_list, eos=self.task.tgt_dict.eos(), move_eos_to_beginning=False):
|
183 |
+
return data_utils.collate_tokens(
|
184 |
+
sample_list,
|
185 |
+
pad_idx=self.padding_idx,
|
186 |
+
eos_idx=eos,
|
187 |
+
left_pad=False,
|
188 |
+
move_eos_to_beginning=move_eos_to_beginning,
|
189 |
+
)
|
190 |
+
|
191 |
+
batch_size = len(sample["target"])
|
192 |
+
gen_target_size = len(gen_target)
|
193 |
+
seq_per_img = gen_target_size // batch_size
|
194 |
+
|
195 |
+
model.train()
|
196 |
+
sample_src_tokens = torch.repeat_interleave(
|
197 |
+
sample['net_input']['src_tokens'], seq_per_img, dim=0
|
198 |
+
)
|
199 |
+
sample_src_lengths = torch.repeat_interleave(
|
200 |
+
sample['net_input']['src_lengths'], seq_per_img, dim=0
|
201 |
+
)
|
202 |
+
sample_patch_images = torch.repeat_interleave(
|
203 |
+
sample['net_input']['patch_images'], seq_per_img, dim=0
|
204 |
+
)
|
205 |
+
sample_patch_masks = torch.repeat_interleave(
|
206 |
+
sample['net_input']['patch_masks'], seq_per_img, dim=0
|
207 |
+
)
|
208 |
+
gen_prev_output_tokens = torch.as_tensor(
|
209 |
+
merge(gen_target, eos=self.task.tgt_dict.bos(), move_eos_to_beginning=True),
|
210 |
+
device=sample["target"].device, dtype=torch.int64
|
211 |
+
)
|
212 |
+
gen_target_tokens = torch.as_tensor(
|
213 |
+
merge(gen_target), device=sample["target"].device, dtype=torch.int64
|
214 |
+
)
|
215 |
+
net_output = model(
|
216 |
+
src_tokens=sample_src_tokens, src_lengths=sample_src_lengths,
|
217 |
+
patch_images=sample_patch_images, patch_masks=sample_patch_masks,
|
218 |
+
prev_output_tokens=gen_prev_output_tokens
|
219 |
+
)
|
220 |
+
|
221 |
+
return net_output, gen_target_tokens
|
222 |
+
|
223 |
+
def get_lprobs_and_target(self, model, net_output, gen_target):
|
224 |
+
if self.constraint_start is not None and self.constraint_end is not None:
|
225 |
+
net_output[0][:, :, 4:self.constraint_start] = -math.inf
|
226 |
+
net_output[0][:, :, self.constraint_end:] = -math.inf
|
227 |
+
lprobs = model.get_normalized_probs(net_output, log_probs=True)
|
228 |
+
if self.ignore_prefix_size > 0:
|
229 |
+
if getattr(lprobs, "batch_first", False):
|
230 |
+
lprobs = lprobs[:, self.ignore_prefix_size :, :].contiguous()
|
231 |
+
gen_target = gen_target[:, self.ignore_prefix_size :].contiguous()
|
232 |
+
else:
|
233 |
+
lprobs = lprobs[self.ignore_prefix_size :, :, :].contiguous()
|
234 |
+
gen_target = gen_target[self.ignore_prefix_size :, :].contiguous()
|
235 |
+
return lprobs, gen_target
|
236 |
+
|
237 |
+
def compute_loss(self, model, sample, reduce=True):
|
238 |
+
gen_target, gen_res, gt_res = self.get_generator_out(model, sample)
|
239 |
+
reward, scores = self.get_reward_and_scores(gen_res, gt_res, device=sample["target"].device)
|
240 |
+
net_output, gen_target_tokens = self.get_net_output(model, sample, gen_target)
|
241 |
+
gen_lprobs, gen_target_tokens = self.get_lprobs_and_target(model, net_output, gen_target_tokens)
|
242 |
+
loss, ntokens = scst_loss(gen_lprobs, gen_target_tokens, reward, ignore_index=self.padding_idx, reduce=reduce)
|
243 |
+
nsentences = gen_target_tokens.size(0)
|
244 |
+
|
245 |
+
return loss, scores.sum(), ntokens, nsentences
|
246 |
+
|
247 |
+
@classmethod
|
248 |
+
def reduce_metrics(cls, logging_outputs) -> None:
|
249 |
+
"""Aggregate logging outputs from data parallel training."""
|
250 |
+
loss_sum = sum(log.get("loss", 0) for log in logging_outputs)
|
251 |
+
score_sum = sum(log.get("score", 0) for log in logging_outputs)
|
252 |
+
ntokens = sum(log.get("ntokens", 0) for log in logging_outputs)
|
253 |
+
nsentences = sum(log.get("nsentences", 0) for log in logging_outputs)
|
254 |
+
sample_size = sum(log.get("sample_size", 0) for log in logging_outputs)
|
255 |
+
|
256 |
+
metrics.log_scalar(
|
257 |
+
"loss", loss_sum / sample_size, sample_size, round=3
|
258 |
+
)
|
259 |
+
metrics.log_scalar(
|
260 |
+
"score", score_sum / nsentences, nsentences, round=3
|
261 |
+
)
|
262 |
+
|
263 |
+
metrics.log_scalar(
|
264 |
+
"ntokens", ntokens, 1, round=3
|
265 |
+
)
|
266 |
+
metrics.log_scalar(
|
267 |
+
"nsentences", nsentences, 1, round=3
|
268 |
+
)
|
269 |
+
metrics.log_scalar(
|
270 |
+
"sample_size", sample_size, 1, round=3
|
271 |
+
)
|
272 |
+
|
273 |
+
@staticmethod
|
274 |
+
def logging_outputs_can_be_summed() -> bool:
|
275 |
+
"""
|
276 |
+
Whether the logging outputs returned by `forward` can be summed
|
277 |
+
across workers prior to calling `reduce_metrics`. Setting this
|
278 |
+
to True will improves distributed training speed.
|
279 |
+
"""
|
280 |
+
return True
|