Class: Daimond::Tensor
- Inherits:
-
Object
- Object
- Daimond::Tensor
- Defined in:
- lib/daimond/tensor.rb
Instance Attribute Summary collapse
-
#_backward ⇒ Object
Returns the value of attribute _backward.
-
#data ⇒ Object
Returns the value of attribute data.
-
#grad ⇒ Object
Returns the value of attribute grad.
-
#label ⇒ Object
Returns the value of attribute label.
-
#op ⇒ Object
Returns the value of attribute op.
-
#prev ⇒ Object
Returns the value of attribute prev.
Class Method Summary collapse
Instance Method Summary collapse
-
#*(other) ⇒ Object
Поэлементное.
- #+(other) ⇒ Object
- #-(other) ⇒ Object
- #backward! ⇒ Object
- #dot(other) ⇒ Object
-
#initialize(data, prev: [], op: nil, label: nil) ⇒ Tensor
constructor
A new instance of Tensor.
- #mean ⇒ Object
- #relu ⇒ Object
- #shape ⇒ Object
- #sigmoid ⇒ Object
- #softmax ⇒ Object
- #sum ⇒ Object
- #to_s ⇒ Object (also: #inspect)
Constructor Details
#initialize(data, prev: [], op: nil, label: nil) ⇒ Tensor
Returns a new instance of Tensor.
8 9 10 11 12 13 14 15 |
# File 'lib/daimond/tensor.rb', line 8 def initialize(data, prev: [], op: nil, label: nil) @data = data.is_a?(Numo::DFloat) ? data : Numo::DFloat[*data] @grad = Numo::DFloat.zeros(*@data.shape) @prev = prev @op = op @label = label @_backward = lambda {} # По умолчанию пустая функция end |
Instance Attribute Details
#_backward ⇒ Object
Returns the value of attribute _backward.
6 7 8 |
# File 'lib/daimond/tensor.rb', line 6 def _backward @_backward end |
#data ⇒ Object
Returns the value of attribute data.
6 7 8 |
# File 'lib/daimond/tensor.rb', line 6 def data @data end |
#grad ⇒ Object
Returns the value of attribute grad.
6 7 8 |
# File 'lib/daimond/tensor.rb', line 6 def grad @grad end |
#label ⇒ Object
Returns the value of attribute label.
6 7 8 |
# File 'lib/daimond/tensor.rb', line 6 def label @label end |
#op ⇒ Object
Returns the value of attribute op.
6 7 8 |
# File 'lib/daimond/tensor.rb', line 6 def op @op end |
#prev ⇒ Object
Returns the value of attribute prev.
6 7 8 |
# File 'lib/daimond/tensor.rb', line 6 def prev @prev end |
Class Method Details
Instance Method Details
#*(other) ⇒ Object
Поэлементное
68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
# File 'lib/daimond/tensor.rb', line 68 def *(other) # Поэлементное other = other.is_a?(Tensor) ? other : Tensor.new(other) left = self right = other out = Tensor.new(@data * other.data, prev: [self, other], op: '*') out._backward = lambda do grad = out.grad left.grad += right.data * grad right.grad += left.data * grad end out end |
#+(other) ⇒ Object
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 |
# File 'lib/daimond/tensor.rb', line 21 def +(other) other = other.is_a?(Tensor) ? other : Tensor.new(other) left = self right = other out = Tensor.new(@data + other.data, prev: [self, other], op: '+') out._backward = lambda do grad = out.grad # Для left (может быть broadcasted, но здесь обычно нет) if grad.shape.length > left.shape.length left.grad += grad.sum(axis: 0) else left.grad += grad end # Для right (bias) — суммируем по batch if grad.shape.length > right.shape.length right.grad += grad.sum(axis: 0) else right.grad += grad end end out end |
#-(other) ⇒ Object
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/daimond/tensor.rb', line 48 def -(other) other = other.is_a?(Tensor) ? other : Tensor.new(other) left = self right = other out = Tensor.new(@data - other.data, prev: [self, other], op: '-') out._backward = lambda do grad = out.grad left.grad += grad if grad.shape.length > right.shape.length right.grad -= grad.sum(axis: 0) else right.grad -= grad end end out end |
#backward! ⇒ Object
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 |
# File 'lib/daimond/tensor.rb', line 186 def backward! # Топологическая сортировка topo = [] visited = [] build_topo = lambda do |v| return if visited.include?(v) visited << v v.prev.each { |child| build_topo.call(child) } topo << v end build_topo.call(self) self.grad = Numo::DFloat[1.0] # seed gradient # Идём в обратном порядке (от loss к входам) topo.reverse.each do |node| node._backward.call end end |
#dot(other) ⇒ Object
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 |
# File 'lib/daimond/tensor.rb', line 83 def dot(other) other = other.is_a?(Tensor) ? other : Tensor.new(other) inner_dim = @data.shape[1] out_dim = other.data.shape[1] # Глобальный счетчик для отладки $rust_count ||= 0 $ruby_count ||= 0 rust_available = defined?(Daimond::Rust) condition = (inner_dim > 100 || out_dim > 50) if rust_available && condition begin rust_a = Daimond::Rust::Tensor.from_array(@data.to_a) rust_b = Daimond::Rust::Tensor.from_array(other.data.to_a) rust_result = rust_a.matmul(rust_b) out = Tensor.new(Numo::DFloat[*rust_result.to_a], prev: [self, other], op: 'dot') out._backward = lambda do grad = out.grad self.grad += grad.dot(other.data.transpose) other.grad += self.data.transpose.dot(grad) end $rust_count += 1 out rescue => e $ruby_count += 1 # Fallback out = Tensor.new(@data.dot(other.data), prev: [self, other], op: 'dot') out._backward = lambda do grad = out.grad self.grad += grad.dot(other.data.transpose) other.grad += self.data.transpose.dot(grad) end out end else $ruby_count += 1 # Ruby version out = Tensor.new(@data.dot(other.data), prev: [self, other], op: 'dot') out._backward = lambda do grad = out.grad self.grad += grad.dot(other.data.transpose) other.grad += self.data.transpose.dot(grad) end out end end |
#mean ⇒ Object
174 175 176 177 178 179 180 181 182 183 184 |
# File 'lib/daimond/tensor.rb', line 174 def mean input = self out = Tensor.new(Numo::DFloat[@data.mean], prev: [self], op: 'mean') n = @data.size out._backward = lambda do input.grad += Numo::DFloat.ones(*input.shape) * (out.grad[0] / n) end out end |
#relu ⇒ Object
136 137 138 139 140 141 142 143 144 145 146 147 148 |
# File 'lib/daimond/tensor.rb', line 136 def relu out_data = @data.map { |x| x > 0 ? x : 0.0 } out = Tensor.new(out_data, prev: [self], op: 'relu') input = self out._backward = lambda do grad = out.grad mask = input.data.map { |x| x > 0 ? 1.0 : 0.0 } input.grad += mask * grad end out end |
#shape ⇒ Object
17 18 19 |
# File 'lib/daimond/tensor.rb', line 17 def shape @data.shape end |
#sigmoid ⇒ Object
150 151 152 153 154 155 156 157 158 159 160 161 |
# File 'lib/daimond/tensor.rb', line 150 def sigmoid input = self s = @data.map { |x| 1.0 / (1.0 + Math.exp(-x)) } out = Tensor.new(s, prev: [self], op: 'sigmoid') out._backward = lambda do grad = out.grad input.grad += (out.data * (1.0 - out.data)) * grad end out end |
#softmax ⇒ Object
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 |
# File 'lib/daimond/tensor.rb', line 223 def softmax input = self # Численная стабильность: вычитаем max по каждой строке max_val = @data.max(axis: 1).reshape(@data.shape[0], 1) exp_data = Numo::NMath.exp(@data - max_val) sum_exp = exp_data.sum(axis: 1).reshape(@data.shape[0], 1) out_data = exp_data / sum_exp out = Tensor.new(out_data, prev: [self], op: 'softmax') # Backward упрощенный (для связки с CrossEntropy) out._backward = lambda do input.grad += out.grad end out end |
#sum ⇒ Object
163 164 165 166 167 168 169 170 171 172 |
# File 'lib/daimond/tensor.rb', line 163 def sum input = self out = Tensor.new(Numo::DFloat[@data.sum], prev: [self], op: 'sum') out._backward = lambda do input.grad += Numo::DFloat.ones(*input.shape) * out.grad[0] end out end |
#to_s ⇒ Object Also known as: inspect
208 209 210 |
# File 'lib/daimond/tensor.rb', line 208 def to_s "Tensor(shape=#{shape}, mean=#{@data.mean.round(4)})" end |