1+ /* *
2+ * @file graph_creation.cpp
3+ * @author Robert Baumgartner (r.baumgartner-1@tudelft.nl)
4+ * @brief
5+ * @version 0.1
6+ * @date 2026-02-17
7+ *
8+ * @copyright Copyright (c) 2026
9+ *
10+ */
11+
12+ #include " graph_creation.h"
13+
14+ #include " add_node.h"
15+ #include " matmul_node.h"
16+ #include " elementwise_mul_node.h"
17+ #include " scalar_op_nodes.h"
18+
19+ using namespace std ;
20+
21+ shared_ptr<Tensor> graph::mul (const shared_ptr<Tensor> left, const shared_ptr<Tensor> right) {
22+ auto res = make_shared<Tensor>((*left) * (*right));
23+ if (left->getRequiresGrad () || right->getRequiresGrad ()){
24+ assert (res->getRequiresGrad ());
25+ res->setCgNode (make_shared<graph::ElementwiseMulNode>(left, right));
26+ }
27+ return res;
28+ }
29+
30+ shared_ptr<Tensor> graph::add (const shared_ptr<Tensor> left, const shared_ptr<Tensor> right) {
31+ auto res = make_shared<Tensor>(*left + *right);
32+ if (left->getRequiresGrad () || right->getRequiresGrad ()){
33+ assert (res->getRequiresGrad ());
34+ res->setCgNode (make_shared<graph::AddNode>(left, right));
35+ }
36+ return res;
37+ }
38+
39+ shared_ptr<Tensor> graph::matmul (const shared_ptr<Tensor> left, const shared_ptr<Tensor> right) {
40+ auto res = make_shared<Tensor>(left->matmul (*right));
41+ if (left->getRequiresGrad () || right->getRequiresGrad ()){
42+ assert (res->getRequiresGrad ());
43+ res->setCgNode (make_shared<graph::MatMulNode>(left, right));
44+ }
45+ return res;
46+ }
47+
48+ shared_ptr<Tensor> graph::mul (const shared_ptr<Tensor> t, ftype scalar) {
49+ auto res = make_shared<Tensor>((*t) * scalar);
50+ if (t->getRequiresGrad ()){
51+ assert (res->getRequiresGrad ());
52+ res->setCgNode (std::make_shared<graph::ScalarMulNode>(t, scalar));
53+ }
54+ return res;
55+ }
56+
57+ shared_ptr<Tensor> graph::mul (ftype scalar, const shared_ptr<Tensor> t) {
58+ return graph::mul (t, scalar);
59+ }
60+
61+ shared_ptr<Tensor> graph::add (const shared_ptr<Tensor> t, ftype scalar) {
62+ auto res = make_shared<Tensor>((*t) + scalar);
63+ if (t->getRequiresGrad ()){
64+ assert (res->getRequiresGrad ());
65+ res->setCgNode (std::make_shared<graph::ScalarAddNode>(t));
66+ }
67+ return res;
68+ }
69+
70+ shared_ptr<Tensor> graph::add (ftype scalar, const shared_ptr<Tensor> t) {
71+ return graph::add (t, scalar);
72+ }
73+
74+ shared_ptr<Tensor> graph::sub (const shared_ptr<Tensor> t, ftype scalar) {
75+ auto res = make_shared<Tensor>((*t) - scalar);
76+ if (t->getRequiresGrad ()){
77+ assert (res->getRequiresGrad ());
78+ res->setCgNode (std::make_shared<graph::ScalarAddNode>(t));
79+ }
80+ return res;
81+ }
82+
83+ shared_ptr<Tensor> graph::div (const shared_ptr<Tensor> t, ftype scalar) {
84+ auto res = make_shared<Tensor>((*t) / scalar);
85+ if (t->getRequiresGrad ()){
86+ assert (res->getRequiresGrad ());
87+ res->setCgNode (std::make_shared<graph::ScalarMulNode>(t, 1 / scalar));
88+ }
89+ return res;
90+ }
0 commit comments