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
use tensor_rs::tensor::Tensor;
use super::{OpTrait, OpHandle};
#[cfg(feature = "use-serde")]
use serde::{Serialize, Deserialize};
#[cfg(feature = "use-serde")]
use std::any::Any;
pub enum Reduction{
None,
Mean,
Sum,
}
#[cfg_attr(feature = "use-serde", derive(Serialize, Deserialize))]
pub struct MSELoss {
#[cfg_attr(feature = "use-serde", serde(skip))]
handle: OpHandle,
}
impl MSELoss {
pub fn new() -> MSELoss {
MSELoss {
handle: OpHandle::new(),
}
}
handle_method!();
}
impl OpTrait for MSELoss {
fn get_name(&self) -> &'static str {
"MSE"
}
fn get_input_size(&self) -> usize {
2
}
fn get_output_size(&self) -> usize {
1
}
fn apply(&self, input: &[Tensor], output: &[Tensor]) {
let tmp = input[0].sub(&input[1]);
let tmp2 = tmp.mul(&tmp);
let tmp3 = tmp2.sum(None, false);
let ret = tmp3.div(&input[0].get_n().mul(&input[0].get_c()));
output[0].swap(&ret);
}
fn grad(&self, input: &[Tensor], output_grad: &[Tensor], input_grad: &[Tensor]) {
if input.len() < 2 {
panic!("MSELoss expect two input, get {}", input.len());
}
if input_grad.len() < 2 {
panic!("MSELoss expect two input gradient tensor, get {}", input_grad.len());
}
if output_grad.is_empty() {
panic!("MSELoss expect one output gradient, get {}", output_grad.len());
}
if ! input[0].same_shape(&input[1]) {
panic!("MSELoss expect two input have the same shape, get {:?}, {:?}", input[0].size(), input[1].size());
}
let tmp1 = input[0].sub(&input[1]);
let tmp2 = tmp1.div(&input[0].numel_tensor());
let tmp3 = tmp2.mul(&output_grad[0]);
input_grad[0].swap(&tmp3);
let tmp1 = input[1].sub(&input[0]);
let tmp2 = tmp1.div(&input[0].numel_tensor());
let tmp3 = tmp2.mul(&output_grad[0]);
input_grad[1].swap(&tmp3);
}
fn get_values(&self) -> Vec<Tensor> {
Vec::new()
}
fn set_values(&self, _v: &[Tensor]) {
}
fn get_grads(&self) -> Vec<Tensor> {
Vec::new()
}
#[cfg(feature = "use-serde")]
fn as_any(&self) -> &dyn Any {
self
}
}
impl Default for MSELoss {
fn default() -> Self {
Self::new()
}
}
#[cfg_attr(feature = "use-serde", derive(Serialize, Deserialize))]
pub struct CrossEntropyLoss {
#[cfg_attr(feature = "use-serde", serde(skip))]
handle: OpHandle,
}
impl CrossEntropyLoss {
pub fn new() -> CrossEntropyLoss {
CrossEntropyLoss {
handle: OpHandle::new(),
}
}
handle_method!();
}
impl OpTrait for CrossEntropyLoss {
fn get_name(&self) -> &'static str {
"CrossEntropyLoss"
}
fn get_input_size(&self) -> usize {
2
}
fn get_output_size(&self) -> usize {
1
}
fn apply(&self, input: &[Tensor], output: &[Tensor]) {
if input.len() < 2 {
panic!("{} expect two input, get {}", self.get_name(), input.len());
}
if input[0].size().len() != (input[1].size().len()+1) {
panic!("{} expect dim+1 and dim, get {}, {}", self.get_name(), input[0].size().len(), input[1].size().len());
}
let class_index = input[1].unsqueeze(1);
let class_score = input[0].gather(1, &class_index);
let val = class_score.neg().add(&input[0].logsumexp(Some(&[1]), true)).mean(None, false);
output[0].swap(&val);
}
fn grad(&self, input: &[Tensor],
output_grad: &[Tensor], input_grad: &[Tensor]) {
let mut dim_order: Vec<usize> = (0..input[0].size().len()).collect();
dim_order[0] = 1;
dim_order[1] = 0;
let smaller = input[0].permute(&dim_order);
let max = smaller.max(Some(&[0]), false);
let smaller = smaller.sub(&max);
let new_label = input[1].unsqueeze(0);
let mut class_dim = vec![1; smaller.size().len()];
class_dim[0] = smaller.size()[0];
let denominator = smaller.exp().sum(Some(&[0]), true).repeat(&class_dim);
let mut tmp_dim = vec![1; smaller.size().len()];
tmp_dim[0] = smaller.size()[0];
let repeated_label = new_label.repeat(&tmp_dim);
#[cfg(feature = "use-f32")]
let class_seq: Vec<f32> = (0..smaller.size()[0]).map(|x| x as f32).collect();
#[cfg(feature = "use-f64")]
let class_seq: Vec<f64> = (0..smaller.size()[0]).map(|x| x as f64).collect();
#[cfg(feature = "use-f32")]
let class_label = Tensor::from_vec_f32(&class_seq, &class_dim);
#[cfg(feature = "use-f64")]
let class_label = Tensor::from_vec_f64(&class_seq, &class_dim);
let mut repeat_dim = smaller.size();
repeat_dim[0] = 1;
let repeated_class = class_label.repeat(&repeat_dim);
let pick = repeated_label.eq_t(&repeated_class);
let smaller_exp = smaller.exp();
let numerator = pick.conditional_select(&smaller_exp.sub(&denominator), &smaller_exp);
#[cfg(feature = "use-f32")]
let grad = numerator.div(&denominator).div(&Tensor::from_vec_f32(&[input[1].numel() as f32], &[1]));
#[cfg(feature = "use-f64")]
let grad = numerator.div(&denominator).div(&Tensor::from_vec_f64(&[input[1].numel() as f64], &[1]));
let grad = grad.permute(&dim_order);
input_grad[0].swap(&grad.mul(&output_grad[0]));
}
fn get_values(&self) -> Vec<Tensor> {
Vec::new()
}
fn set_values(&self, _v: &[Tensor]) {
}
fn get_grads(&self) -> Vec<Tensor> {
Vec::new()
}
#[cfg(feature = "use-serde")]
fn as_any(&self) -> &dyn Any {
self
}
}
impl Default for CrossEntropyLoss {
fn default() -> Self {
Self::new()
}
}
#[cfg_attr(feature = "use-serde", derive(Serialize, Deserialize))]
pub struct BCEWithLogitsLoss {
#[cfg_attr(feature = "use-serde", serde(skip))]
handle: OpHandle,
}
impl BCEWithLogitsLoss {
pub fn new() -> BCEWithLogitsLoss {
BCEWithLogitsLoss {
handle: OpHandle::new(),
}
}
handle_method!();
}
impl OpTrait for BCEWithLogitsLoss {
fn get_name(&self) -> &'static str {
"BCEWithLogitsLoss"
}
fn get_input_size(&self) -> usize {
2
}
fn get_output_size(&self) -> usize {
1
}
fn apply(&self, input: &[Tensor], output: &[Tensor]) {
if input.len() != self.get_input_size() {
panic!("{} expect two input, get {}", self.get_name(), input.len());
}
let ret_all = input[1].mul(&input[0].neg().log1pexp())
.add(&(input[1].neg().add(&input[1].ones_like())).mul(&input[0].log1pexp()));
let tmp3 = ret_all.sum(None, false);
let ret = tmp3.div(&input[0].get_n().mul(&input[0].get_c()));
output[0].swap(&ret);
}
fn grad(&self, input: &[Tensor],
output_grad: &[Tensor],
input_grad: &[Tensor]) {
let ones = Tensor::ones_like(&input[0]);
let tmp1 = input[1].neg().div(&input[0].exp().add(&ones));
let tmp2 = input[1].neg().add(&ones).div(&input[0].neg().exp().add(&ones));
let tmp3 = tmp1.add(&tmp2);
let tmp4 = tmp3.mul(&output_grad[0]);
let zeros = Tensor::zeros_like(&input[0]);
input_grad[0].swap(&tmp4);
input_grad[1].swap(&zeros);
}
fn get_values(&self) -> Vec<Tensor> {
Vec::new()
}
fn set_values(&self, _v: &[Tensor]) {
}
fn get_grads(&self) -> Vec<Tensor> {
Vec::new()
}
#[cfg(feature = "use-serde")]
fn as_any(&self) -> &dyn Any {
self
}
}
impl Default for BCEWithLogitsLoss {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_cross_entropy_loss() {
let a = Tensor::from_vec_f64(&vec![1., 2., 3., 4., 5., 6., ], &vec![3, 2]);
let b = Tensor::from_vec_f64(&vec![0., 0., 1., ], &vec![3]);
let c = CrossEntropyLoss::new();
let d = Tensor::new();
c.apply(&[a.ref_copy(), b.ref_copy()], &[d.ref_copy()]);
assert!((d.get_scale_f64() - 0.97992826).abs() < 0.001);
}
}