spmm.cpp 13.1 KB
Newer Older
1
#ifdef WITH_PYTHON
rusty1s's avatar
rusty1s committed
2
#include <Python.h>
3
#endif
rusty1s's avatar
matmul  
rusty1s committed
4
5
6
7
8
9
10
11
#include <torch/script.h>

#include "cpu/spmm_cpu.h"

#ifdef WITH_CUDA
#include "cuda/spmm_cuda.h"
#endif

rusty1s's avatar
rusty1s committed
12
#ifdef _WIN32
13
#ifdef WITH_PYTHON
rusty1s's avatar
rusty1s committed
14
15
16
17
18
#ifdef WITH_CUDA
PyMODINIT_FUNC PyInit__spmm_cuda(void) { return NULL; }
#else
PyMODINIT_FUNC PyInit__spmm_cpu(void) { return NULL; }
#endif
rusty1s's avatar
rusty1s committed
19
#endif
20
#endif
rusty1s's avatar
rusty1s committed
21

rusty1s's avatar
matmul  
rusty1s committed
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
std::tuple<torch::Tensor, torch::optional<torch::Tensor>>
spmm_fw(torch::Tensor rowptr, torch::Tensor col,
        torch::optional<torch::Tensor> optional_value, torch::Tensor mat,
        std::string reduce) {
  if (rowptr.device().is_cuda()) {
#ifdef WITH_CUDA
    return spmm_cuda(rowptr, col, optional_value, mat, reduce);
#else
    AT_ERROR("Not compiled with CUDA support");
#endif
  } else {
    return spmm_cpu(rowptr, col, optional_value, mat, reduce);
  }
}

torch::Tensor spmm_value_bw(torch::Tensor row, torch::Tensor rowptr,
                            torch::Tensor col, torch::Tensor mat,
                            torch::Tensor grad, std::string reduce) {
40
  if (row.device().is_cuda()) {
rusty1s's avatar
matmul  
rusty1s committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#ifdef WITH_CUDA
    return spmm_value_bw_cuda(row, rowptr, col, mat, grad, reduce);
#else
    AT_ERROR("Not compiled with CUDA support");
#endif
  } else {
    return spmm_value_bw_cpu(row, rowptr, col, mat, grad, reduce);
  }
}

using torch::autograd::AutogradContext;
using torch::autograd::Variable;
using torch::autograd::variable_list;

class SPMMSum : public torch::autograd::Function<SPMMSum> {
public:
  static variable_list forward(AutogradContext *ctx,
58
                               torch::optional<Variable> opt_row,
rusty1s's avatar
matmul  
rusty1s committed
59
                               Variable rowptr, Variable col, Variable value,
60
61
                               torch::optional<Variable> opt_colptr,
                               torch::optional<Variable> opt_csr2csc,
rusty1s's avatar
rusty1s committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
                               Variable mat, bool has_value) {

    if (has_value && torch::autograd::any_variable_requires_grad({value})) {
      AT_ASSERTM(opt_row.has_value(), "Argument `row` is missing");
    }

    if (torch::autograd::any_variable_requires_grad({mat})) {
      AT_ASSERTM(opt_row.has_value(), "Argument `row` is missing");
      AT_ASSERTM(opt_colptr.has_value(), "Argument `colptr` is missing");
      AT_ASSERTM(opt_csr2csc.has_value(), "Argument `csr2csc` is missing");
    }

    auto row = opt_row.has_value() ? opt_row.value() : col;
    auto colptr = opt_colptr.has_value() ? opt_colptr.value() : col;
    auto csr2csc = opt_csr2csc.has_value() ? opt_csr2csc.value() : col;
77
78

    torch::optional<torch::Tensor> opt_value = torch::nullopt;
rusty1s's avatar
rusty1s committed
79
    if (has_value)
80
81
82
      opt_value = value;

    auto out = std::get<0>(spmm_fw(rowptr, col, opt_value, mat, "sum"));
rusty1s's avatar
rusty1s committed
83
    ctx->saved_data["has_value"] = has_value;
rusty1s's avatar
matmul  
rusty1s committed
84
85
86
87
88
    ctx->save_for_backward({row, rowptr, col, value, colptr, csr2csc, mat});
    return {out};
  }

  static variable_list backward(AutogradContext *ctx, variable_list grad_outs) {
rusty1s's avatar
rusty1s committed
89
    auto has_value = ctx->saved_data["has_value"].toBool();
rusty1s's avatar
matmul  
rusty1s committed
90
91
    auto grad_out = grad_outs[0];
    auto saved = ctx->get_saved_variables();
92
93
    auto row = saved[0], rowptr = saved[1], col = saved[2], value = saved[3],
         colptr = saved[4], csr2csc = saved[5], mat = saved[6];
rusty1s's avatar
matmul  
rusty1s committed
94
95

    auto grad_value = Variable();
rusty1s's avatar
rusty1s committed
96
    if (has_value > 0 && torch::autograd::any_variable_requires_grad({value})) {
rusty1s's avatar
matmul  
rusty1s committed
97
98
99
100
101
      grad_value = spmm_value_bw(row, rowptr, col, mat, grad_out, "sum");
    }

    auto grad_mat = Variable();
    if (torch::autograd::any_variable_requires_grad({mat})) {
102
      torch::optional<torch::Tensor> opt_value = torch::nullopt;
rusty1s's avatar
rusty1s committed
103
      if (has_value)
rusty1s's avatar
rusty1s committed
104
        opt_value = value.view({-1, 1}).index_select(0, csr2csc).view(-1);
105

rusty1s's avatar
matmul  
rusty1s committed
106
      grad_mat = std::get<0>(spmm_fw(colptr, row.index_select(0, csr2csc),
107
                                     opt_value, grad_out, "sum"));
rusty1s's avatar
matmul  
rusty1s committed
108
109
110
    }

    return {Variable(), Variable(), Variable(), grad_value,
rusty1s's avatar
rusty1s committed
111
            Variable(), Variable(), grad_mat,   Variable()};
rusty1s's avatar
matmul  
rusty1s committed
112
113
114
  }
};

115
116
117
118
119
120
121
122
class SPMMMean : public torch::autograd::Function<SPMMMean> {
public:
  static variable_list forward(AutogradContext *ctx,
                               torch::optional<Variable> opt_row,
                               Variable rowptr, Variable col, Variable value,
                               torch::optional<Variable> opt_rowcount,
                               torch::optional<Variable> opt_colptr,
                               torch::optional<Variable> opt_csr2csc,
rusty1s's avatar
rusty1s committed
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
                               Variable mat, bool has_value) {

    if (has_value && torch::autograd::any_variable_requires_grad({value})) {
      AT_ASSERTM(opt_row.has_value(), "Argument `row` is missing");
    }

    if (torch::autograd::any_variable_requires_grad({mat})) {
      AT_ASSERTM(opt_row.has_value(), "Argument `row` is missing");
      AT_ASSERTM(opt_rowcount.has_value(), "Argument `rowcount` is missing");
      AT_ASSERTM(opt_colptr.has_value(), "Argument `colptr` is missing");
      AT_ASSERTM(opt_csr2csc.has_value(), "Argument `csr2csc` is missing");
    }

    auto row = opt_row.has_value() ? opt_row.value() : col;
    auto rowcount = opt_rowcount.has_value() ? opt_rowcount.value() : col;
    auto colptr = opt_colptr.has_value() ? opt_colptr.value() : col;
    auto csr2csc = opt_csr2csc.has_value() ? opt_csr2csc.value() : col;
140
141

    torch::optional<torch::Tensor> opt_value = torch::nullopt;
rusty1s's avatar
rusty1s committed
142
    if (has_value)
143
144
145
      opt_value = value;

    auto out = std::get<0>(spmm_fw(rowptr, col, opt_value, mat, "mean"));
rusty1s's avatar
rusty1s committed
146
    ctx->saved_data["has_value"] = has_value;
147
148
149
150
151
152
    ctx->save_for_backward(
        {row, rowptr, col, value, rowcount, colptr, csr2csc, mat});
    return {out};
  }

  static variable_list backward(AutogradContext *ctx, variable_list grad_outs) {
rusty1s's avatar
rusty1s committed
153
    auto has_value = ctx->saved_data["has_value"].toBool();
154
155
156
157
158
159
160
    auto grad_out = grad_outs[0];
    auto saved = ctx->get_saved_variables();
    auto row = saved[0], rowptr = saved[1], col = saved[2], value = saved[3],
         rowcount = saved[4], colptr = saved[5], csr2csc = saved[6],
         mat = saved[7];

    auto grad_value = Variable();
rusty1s's avatar
rusty1s committed
161
    if (has_value > 0 && torch::autograd::any_variable_requires_grad({value})) {
162
163
164
165
166
167
      grad_value = spmm_value_bw(row, rowptr, col, mat, grad_out, "mean");
    }

    auto grad_mat = Variable();
    if (torch::autograd::any_variable_requires_grad({mat})) {
      row = row.index_select(0, csr2csc);
rusty1s's avatar
rusty1s committed
168
      rowcount = rowcount.index_select(0, row).toType(mat.scalar_type());
rusty1s's avatar
rusty1s committed
169
      rowcount.masked_fill_(rowcount < 1, 1);
170

rusty1s's avatar
rusty1s committed
171
      if (has_value > 0)
rusty1s's avatar
rusty1s committed
172
173
        rowcount =
            value.view({-1, 1}).index_select(0, csr2csc).view(-1).div(rowcount);
174
175
176
177
178
179
      else
        rowcount.pow_(-1);

      grad_mat = std::get<0>(spmm_fw(colptr, row, rowcount, grad_out, "sum"));
    }

rusty1s's avatar
rusty1s committed
180
181
    return {Variable(), Variable(), Variable(), grad_value, Variable(),
            Variable(), Variable(), grad_mat,   Variable()};
182
183
184
  }
};

rusty1s's avatar
rusty1s committed
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
class SPMMMin : public torch::autograd::Function<SPMMMin> {
public:
  static variable_list forward(AutogradContext *ctx, Variable rowptr,
                               Variable col, Variable value, Variable mat,
                               bool has_value) {

    torch::optional<torch::Tensor> opt_value = torch::nullopt;
    if (has_value)
      opt_value = value;

    auto result = spmm_fw(rowptr, col, opt_value, mat, "min");
    auto out = std::get<0>(result);
    auto arg_out = std::get<1>(result).value();
    ctx->saved_data["has_value"] = has_value;
    ctx->save_for_backward({col, value, mat, arg_out});
    ctx->mark_non_differentiable({arg_out});
    return {out, arg_out};
  }

  static variable_list backward(AutogradContext *ctx, variable_list grad_outs) {
    auto has_value = ctx->saved_data["has_value"].toBool();
    auto grad_out = grad_outs[0];
    auto saved = ctx->get_saved_variables();
    auto col = saved[0], value = saved[1], mat = saved[2], arg_out = saved[3];

    auto invalid_arg_mask = arg_out == col.size(0);
    arg_out = arg_out.masked_fill(invalid_arg_mask, 0);

    auto grad_value = Variable();
    if (has_value > 0 && torch::autograd::any_variable_requires_grad({value})) {
      auto ind = col.index_select(0, arg_out.flatten()).view_as(arg_out);
      auto out = mat.gather(-2, ind);
      out.mul_(grad_out);
      out.masked_fill_(invalid_arg_mask, 0);

      grad_value = torch::zeros_like(value);
      grad_value.scatter_add_(0, arg_out.flatten(), out.flatten());
    }

    auto grad_mat = Variable();
    if (torch::autograd::any_variable_requires_grad({mat})) {
      if (has_value > 0) {
rusty1s's avatar
rusty1s committed
227
228
229
230
        value = value.view({-1, 1})
                    .index_select(0, arg_out.flatten())
                    .view_as(arg_out)
                    .mul_(grad_out);
rusty1s's avatar
rusty1s committed
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
      } else
        value = grad_out;

      value.masked_fill_(invalid_arg_mask, 0);
      auto ind = col.index_select(0, arg_out.flatten()).view_as(arg_out);

      grad_mat = torch::zeros_like(mat);
      grad_mat.scatter_add_(-2, ind, value);
    }

    return {Variable(), Variable(), grad_value, grad_mat, Variable()};
  }
};

class SPMMMax : public torch::autograd::Function<SPMMMax> {
public:
  static variable_list forward(AutogradContext *ctx, Variable rowptr,
                               Variable col, Variable value, Variable mat,
                               bool has_value) {

    torch::optional<torch::Tensor> opt_value = torch::nullopt;
    if (has_value)
      opt_value = value;

    auto result = spmm_fw(rowptr, col, opt_value, mat, "max");
    auto out = std::get<0>(result);
    auto arg_out = std::get<1>(result).value();
    ctx->saved_data["has_value"] = has_value;
    ctx->save_for_backward({col, value, mat, arg_out});
    ctx->mark_non_differentiable({arg_out});
    return {out, arg_out};
  }

  static variable_list backward(AutogradContext *ctx, variable_list grad_outs) {
    auto has_value = ctx->saved_data["has_value"].toBool();
    auto grad_out = grad_outs[0];
    auto saved = ctx->get_saved_variables();
    auto col = saved[0], value = saved[1], mat = saved[2], arg_out = saved[3];

    auto invalid_arg_mask = arg_out == col.size(0);
    arg_out = arg_out.masked_fill(invalid_arg_mask, 0);

    auto grad_value = Variable();
    if (has_value > 0 && torch::autograd::any_variable_requires_grad({value})) {
      auto ind = col.index_select(0, arg_out.flatten()).view_as(arg_out);
      auto out = mat.gather(-2, ind);
      out.mul_(grad_out);
      out.masked_fill_(invalid_arg_mask, 0);

      grad_value = torch::zeros_like(value);
      grad_value.scatter_add_(0, arg_out.flatten(), out.flatten());
    }

    auto grad_mat = Variable();
    if (torch::autograd::any_variable_requires_grad({mat})) {
      if (has_value > 0) {
rusty1s's avatar
rusty1s committed
287
288
289
290
        value = value.view({-1, 1})
                    .index_select(0, arg_out.flatten())
                    .view_as(arg_out)
                    .mul_(grad_out);
rusty1s's avatar
rusty1s committed
291
292
293
294
295
296
297
298
299
300
301
302
303
304
      } else
        value = grad_out;

      value.masked_fill_(invalid_arg_mask, 0);
      auto ind = col.index_select(0, arg_out.flatten()).view_as(arg_out);

      grad_mat = torch::zeros_like(mat);
      grad_mat.scatter_add_(-2, ind, value);
    }

    return {Variable(), Variable(), grad_value, grad_mat, Variable()};
  }
};

Daniel Falbel's avatar
Daniel Falbel committed
305
SPARSE_API torch::Tensor spmm_sum(torch::optional<torch::Tensor> opt_row,
rusty1s's avatar
matmul  
rusty1s committed
306
                       torch::Tensor rowptr, torch::Tensor col,
307
308
309
                       torch::optional<torch::Tensor> opt_value,
                       torch::optional<torch::Tensor> opt_colptr,
                       torch::optional<torch::Tensor> opt_csr2csc,
rusty1s's avatar
matmul  
rusty1s committed
310
                       torch::Tensor mat) {
rusty1s's avatar
rusty1s committed
311
  auto value = opt_value.has_value() ? opt_value.value() : col;
312
  return SPMMSum::apply(opt_row, rowptr, col, value, opt_colptr, opt_csr2csc,
rusty1s's avatar
rusty1s committed
313
                        mat, opt_value.has_value())[0];
314
315
}

Daniel Falbel's avatar
Daniel Falbel committed
316
SPARSE_API torch::Tensor spmm_mean(torch::optional<torch::Tensor> opt_row,
317
318
319
320
321
322
                        torch::Tensor rowptr, torch::Tensor col,
                        torch::optional<torch::Tensor> opt_value,
                        torch::optional<torch::Tensor> opt_rowcount,
                        torch::optional<torch::Tensor> opt_colptr,
                        torch::optional<torch::Tensor> opt_csr2csc,
                        torch::Tensor mat) {
rusty1s's avatar
rusty1s committed
323
  auto value = opt_value.has_value() ? opt_value.value() : col;
324
  return SPMMMean::apply(opt_row, rowptr, col, value, opt_rowcount, opt_colptr,
rusty1s's avatar
rusty1s committed
325
                         opt_csr2csc, mat, opt_value.has_value())[0];
rusty1s's avatar
matmul  
rusty1s committed
326
327
}

Daniel Falbel's avatar
Daniel Falbel committed
328
SPARSE_API std::tuple<torch::Tensor, torch::Tensor>
rusty1s's avatar
rusty1s committed
329
330
331
332
333
334
335
spmm_min(torch::Tensor rowptr, torch::Tensor col,
         torch::optional<torch::Tensor> opt_value, torch::Tensor mat) {
  auto value = opt_value.has_value() ? opt_value.value() : col;
  auto result = SPMMMin::apply(rowptr, col, value, mat, opt_value.has_value());
  return std::make_tuple(result[0], result[1]);
}

Daniel Falbel's avatar
Daniel Falbel committed
336
SPARSE_API std::tuple<torch::Tensor, torch::Tensor>
rusty1s's avatar
rusty1s committed
337
338
339
340
341
342
343
spmm_max(torch::Tensor rowptr, torch::Tensor col,
         torch::optional<torch::Tensor> opt_value, torch::Tensor mat) {
  auto value = opt_value.has_value() ? opt_value.value() : col;
  auto result = SPMMMax::apply(rowptr, col, value, mat, opt_value.has_value());
  return std::make_tuple(result[0], result[1]);
}

344
345
static auto registry = torch::RegisterOperators()
                           .op("torch_sparse::spmm_sum", &spmm_sum)
rusty1s's avatar
rusty1s committed
346
347
348
                           .op("torch_sparse::spmm_mean", &spmm_mean)
                           .op("torch_sparse::spmm_min", &spmm_min)
                           .op("torch_sparse::spmm_max", &spmm_max);