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
use tch::{Kind, Reduction, Tensor};
use crate::TransformerError;
trait Reduce {
type Error;
fn reduce(&self, t: &Tensor) -> Result<Tensor, Self::Error>;
}
impl Reduce for Reduction {
type Error = TransformerError;
fn reduce(&self, t: &Tensor) -> Result<Tensor, Self::Error> {
match self {
Reduction::None => Ok(t.shallow_clone()),
Reduction::Mean => Ok(t.f_mean(t.kind())?),
Reduction::Sum => Ok(t.f_sum(t.kind())?),
Reduction::Other(_) => unimplemented!(),
}
}
}
pub struct CrossEntropyLoss {
ignore_index: i64,
label_smoothing: Option<f64>,
reduction: Reduction,
}
impl CrossEntropyLoss {
pub fn new(ignore_index: i64, label_smoothing: Option<f64>, reduction: Reduction) -> Self {
CrossEntropyLoss {
ignore_index,
label_smoothing,
reduction,
}
}
pub fn forward(
&self,
logits: &Tensor,
targets: &Tensor,
target_mask: Option<&Tensor>,
) -> Result<Tensor, TransformerError> {
let (_, n_classes) = logits.size2()?;
let log_probs = logits.f_log_softmax(-1, logits.kind())?;
match self.label_smoothing {
Some(label_smoothing) => {
let token_mask = targets.f_ne(self.ignore_index)?;
let targets_non_negative =
targets.f_where_scalarother(&targets.f_ne(self.ignore_index)?, 0)?;
let smoothed_targets = tch::no_grad(|| match target_mask {
None => {
Tensor::f_full_like(&log_probs, label_smoothing / (n_classes - 1) as f64)?
.f_scatter_value(
1,
&targets_non_negative.f_unsqueeze(1)?,
1. - label_smoothing,
)
}
Some(target_mask) => {
let batch_probs = label_smoothing
/ target_mask
.f_sum_dim_intlist(&[-1], false, Kind::Float)?
.f_sub_scalar(1)?;
Tensor::f_zeros_like(&log_probs)?
.f_add_(&batch_probs.f_unsqueeze(-1)?)?
.f_mul(&target_mask.to_kind(Kind::Float))?
.f_scatter_value(
1,
&targets_non_negative.f_unsqueeze(1)?,
1. - label_smoothing,
)
}
})?;
let losses = (smoothed_targets.f_neg()?.f_mul(&log_probs)?).f_sum_dim_intlist(
&[-1],
false,
log_probs.kind(),
)?;
Ok(self.reduction.reduce(&losses.masked_select(&token_mask))?)
}
None => Ok(log_probs.f_nll_loss::<&Tensor>(
targets,
None,
self.reduction,
self.ignore_index,
)?),
}
}
}
#[cfg(test)]
mod tests {
use std::convert::TryInto;
use approx::assert_abs_diff_eq;
use ndarray::{array, ArrayD};
use tch::{Reduction, Tensor};
use crate::loss::CrossEntropyLoss;
#[test]
fn cross_entropy_loss_without_label_smoothing() {
let logits = Tensor::of_slice(&[-1., -1., 1., -1., -1.]).view([1, 5]);
let targets = Tensor::of_slice(&[2i64]).view([1]);
let cross_entropy_loss = CrossEntropyLoss::new(-1, None, Reduction::None);
let loss: ArrayD<f32> = (&cross_entropy_loss.forward(&logits, &targets, None).unwrap())
.try_into()
.unwrap();
assert_abs_diff_eq!(loss, array![0.432653].into_dyn(), epsilon = 1e-6);
}
#[test]
fn cross_entropy_with_label_smoothing() {
let logits = Tensor::of_slice(&[-1., -1., 1., -1., -1.]).view([1, 5]);
let targets = Tensor::of_slice(&[2i64]).view([1]);
let cross_entropy_loss = CrossEntropyLoss::new(-1, Some(0.1), Reduction::None);
let loss: ArrayD<f32> = (&cross_entropy_loss.forward(&logits, &targets, None).unwrap())
.try_into()
.unwrap();
assert_abs_diff_eq!(loss, array![0.632653].into_dyn(), epsilon = 1e-6);
}
#[test]
fn cross_entropy_with_label_smoothing_and_mask() {
let logits = Tensor::of_slice(&[-1., -1., 1., -1., -1.]).view([1, 5]);
let target_mask = Tensor::of_slice(&[true, false, true, false, true]).view([1, 5]);
let targets = Tensor::of_slice(&[2i64]).view([1]);
let cross_entropy_loss = CrossEntropyLoss::new(-1, Some(0.1), Reduction::None);
let loss: ArrayD<f32> = (&cross_entropy_loss
.forward(&logits, &targets, Some(&target_mask))
.unwrap())
.try_into()
.unwrap();
assert_abs_diff_eq!(loss, array![0.632653].into_dyn(), epsilon = 1e-6);
}
}