Class: GRX::Tensor

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/grx/tensor.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(storage, shape, strides: nil, offset: 0, requires_grad: false) ⇒ Tensor

Returns a new instance of Tensor.



8
9
10
11
12
13
14
15
16
17
# File 'lib/grx/tensor.rb', line 8

def initialize(storage, shape, strides: nil, offset: 0, requires_grad: false)
  @storage       = storage
  @shape         = shape
  @offset        = offset
  @strides       = strides || _calc_strides(shape)
  @requires_grad = requires_grad
  @grad          = nil
  @backward_fn   = nil
  @_grafo_hijos  = []
end

Instance Attribute Details

#backward_fnObject

Returns the value of attribute backward_fn.



6
7
8
# File 'lib/grx/tensor.rb', line 6

def backward_fn
  @backward_fn
end

#gradObject

Returns the value of attribute grad.



6
7
8
# File 'lib/grx/tensor.rb', line 6

def grad
  @grad
end

#offsetObject (readonly)

Returns the value of attribute offset.



5
6
7
# File 'lib/grx/tensor.rb', line 5

def offset
  @offset
end

#requires_gradObject

Returns the value of attribute requires_grad.



6
7
8
# File 'lib/grx/tensor.rb', line 6

def requires_grad
  @requires_grad
end

#shapeObject (readonly)

Returns the value of attribute shape.



5
6
7
# File 'lib/grx/tensor.rb', line 5

def shape
  @shape
end

#storageObject (readonly)

Returns the value of attribute storage.



5
6
7
# File 'lib/grx/tensor.rb', line 5

def storage
  @storage
end

#stridesObject (readonly)

Returns the value of attribute strides.



5
6
7
# File 'lib/grx/tensor.rb', line 5

def strides
  @strides
end

Class Method Details

._alloc_raw(n) ⇒ Object



696
697
698
699
700
701
702
703
704
705
706
707
708
# File 'lib/grx/tensor.rb', line 696

def self._alloc_raw(n)
  if CAPI::LOADED
    ptr = CAPI.grx_alloc(n)
    raise StorageError, "grx_alloc OOM" if ptr.null?
    s = Storage.allocate
    s.instance_variable_set(:@size, n)
    s.instance_variable_set(:@ptr,  ptr)
    ObjectSpace.define_finalizer(s, Storage.make_finalizer(ptr))
    s
  else
    Storage.new(Array.new(n, 0.0))
  end
end

.create(array_valores, shape, requires_grad: false) ⇒ Object


FACTORIES



23
24
25
# File 'lib/grx/tensor.rb', line 23

def self.create(array_valores, shape, requires_grad: false)
  new(Storage.new(array_valores), shape, requires_grad: requires_grad)
end

.he_normal(shape, requires_grad: false) ⇒ Object

He normal initialization (optimal for layers with ReLU)



53
54
55
56
57
58
59
60
# File 'lib/grx/tensor.rb', line 53

def self.he_normal(shape, requires_grad: false)
  # fan_in = number of inputs = last dim or penultimate if 2D
  fan_in = shape.size >= 2 ? shape[-1] : shape[0]
  n = shape.reduce(1, :*)
  s = _alloc_raw(n)
  CAPI.grx_init_he_normal(s.ptr, n, fan_in) if CAPI::LOADED
  new(s, shape, requires_grad: requires_grad)
end

.ones(shape, requires_grad: false) ⇒ Object



31
32
33
# File 'lib/grx/tensor.rb', line 31

def self.ones(shape, requires_grad: false)
  create(Array.new(shape.reduce(1,:*), 1.0), shape, requires_grad: requires_grad)
end

.ones_like(t, requires_grad: false) ⇒ Object



39
40
41
# File 'lib/grx/tensor.rb', line 39

def self.ones_like(t, requires_grad: false)
  ones(t.shape, requires_grad: requires_grad)
end

.xavier_uniform(shape, requires_grad: false) ⇒ Object

Xavier uniform initialization (optimal for linear layers with tanh/sigmoid)



44
45
46
47
48
49
50
# File 'lib/grx/tensor.rb', line 44

def self.xavier_uniform(shape, requires_grad: false)
  fan_in, fan_out = shape[-2] || 1, shape[-1] || 1
  n = shape.reduce(1, :*)
  s = _alloc_raw(n)
  CAPI.grx_init_xavier_uniform(s.ptr, n, fan_in, fan_out) if CAPI::LOADED
  new(s, shape, requires_grad: requires_grad)
end

.zeros(shape, requires_grad: false) ⇒ Object



27
28
29
# File 'lib/grx/tensor.rb', line 27

def self.zeros(shape, requires_grad: false)
  create(Array.new(shape.reduce(1,:*), 0.0), shape, requires_grad: requires_grad)
end

.zeros_like(t, requires_grad: false) ⇒ Object



35
36
37
# File 'lib/grx/tensor.rb', line 35

def self.zeros_like(t, requires_grad: false)
  zeros(t.shape, requires_grad: requires_grad)
end

Instance Method Details

#*(other) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/grx/tensor.rb', line 108

def *(other)
  case other
  when Tensor
    raise ShapeError, "Incompatible shapes: #{@shape} vs #{other.shape}" if @shape != other.shape
    r = Tensor.new(_binop(:grx_mul, other), @shape)
    if requires_grad || other.requires_grad
      r.requires_grad = true
      a, b = self, other
      r._grafo_hijos.push(a, b)
      r.backward_fn = ->(g) {
        a.agregar_gradiente(g * b) if a.requires_grad
        b.agregar_gradiente(g * a) if b.requires_grad
      }
    end
    r
  when Numeric
    scale(other.to_f)
  else
    raise TypeError, "Cannot multiply Tensor with #{other.class}"
  end
end

#+(other) ⇒ Object


ARITHMETIC OPERATIONS (with autograd)



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/grx/tensor.rb', line 66

def +(other)
  case other
  when Tensor
    raise ShapeError, "Incompatible shapes: #{@shape} vs #{other.shape}" if @shape != other.shape
    r = Tensor.new(_binop(:grx_add, other), @shape)
    if requires_grad || other.requires_grad
      r.requires_grad = true
      r._grafo_hijos.push(self, other)
      r.backward_fn = ->(g) {
        agregar_gradiente(g)       if requires_grad
        other.agregar_gradiente(g) if other.requires_grad
      }
    end
    r
  when Numeric
    add_scalar(other.to_f)
  else
    raise TypeError, "Cannot add Tensor with #{other.class}"
  end
end

#-(other) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/grx/tensor.rb', line 87

def -(other)
  case other
  when Tensor
    raise ShapeError, "Incompatible shapes: #{@shape} vs #{other.shape}" if @shape != other.shape
    r = Tensor.new(_binop(:grx_sub, other), @shape)
    if requires_grad || other.requires_grad
      r.requires_grad = true
      r._grafo_hijos.push(self, other)
      r.backward_fn = ->(g) {
        agregar_gradiente(g)              if requires_grad
        other.agregar_gradiente(g.negate) if other.requires_grad
      }
    end
    r
  when Numeric
    add_scalar(-other.to_f)
  else
    raise TypeError, "Cannot subtract Tensor with #{other.class}"
  end
end

#-@Object



153
154
155
# File 'lib/grx/tensor.rb', line 153

def -@
  negate
end

#/(other) ⇒ Object



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/grx/tensor.rb', line 130

def /(other)
  case other
  when Tensor
    raise ShapeError, "Incompatible shapes: #{@shape} vs #{other.shape}" if @shape != other.shape
    r = Tensor.new(_binop(:grx_div, other), @shape)
    if requires_grad || other.requires_grad
      r.requires_grad = true
      a, b = self, other
      r._grafo_hijos.push(a, b)
      r.backward_fn = ->(g) {
        # d(a/b)/da = 1/b,  d(a/b)/db = -a/b^2
        a.agregar_gradiente(g / b)                    if a.requires_grad
        b.agregar_gradiente((g * a).negate / (b * b)) if b.requires_grad
      }
    end
    r
  when Numeric
    scale(1.0 / other.to_f)
  else
    raise TypeError, "Cannot divide Tensor with #{other.class}"
  end
end

#<=>(other) ⇒ Object



650
651
652
653
654
655
656
657
658
659
# File 'lib/grx/tensor.rb', line 650

def <=>(other)
  case other
  when Tensor
    (numel == 1 && other.numel == 1) ? item <=> other.item : nil
  when Numeric
    numel == 1 ? item <=> other.to_f : nil
  else
    nil
  end
end

#_grafo_hijosObject



529
530
531
# File 'lib/grx/tensor.rb', line 529

def _grafo_hijos
  @_grafo_hijos
end

#_matmul_no_grad(other) ⇒ Object

Matmul without autograd — for internal backward_fn usage

Raises:



587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
# File 'lib/grx/tensor.rb', line 587

def _matmul_no_grad(other)
  raise DimensionError, "matmul requires 2D tensors" unless @shape.size == 2 && other.shape.size == 2
  m, k = @shape; k2, n = other.shape
  raise ShapeError, "Incompatible dimensions" if k != k2
  a_c = _contiguous? ? self : contiguous
  b_c = other._contiguous? ? other : other.contiguous
  out = _alloc_storage(m * n)
  if CAPI::LOADED
    CAPI.grx_matmul(a_c.storage.ptr, b_c.storage.ptr, out.ptr, m, k, n)
  else
    result = Array.new(m * n, 0.0)
    m.times { |i| k.times { |kk| aik = a_c.storage.read(i*k+kk)
      n.times { |j| result[i*n+j] += aik * b_c.storage.read(kk*n+j) } } }
    return Tensor.new(Storage.new(result), [m, n])
  end
  Tensor.new(out, [m, n])
end

#_transpose_viewObject

Transpose view without autograd — for internal backward pass

Raises:



579
580
581
582
583
584
# File 'lib/grx/tensor.rb', line 579

def _transpose_view
  raise DimensionError, "transpose only supports 2D tensors" if @shape.size != 2
  Tensor.new(@storage, [@shape[1], @shape[0]],
             strides: [@strides[1], @strides[0]],
             offset: @offset, requires_grad: false)
end

#absObject


ELEMENT-WISE MATH (with autograd)



205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/grx/tensor.rb', line 205

def abs
  r = _unary_c(:grx_abs) { |v| v.abs }
  if requires_grad
    r.requires_grad = true; r._grafo_hijos << self
    src = self
    r.backward_fn = ->(g) {
      # d|x|/dx = sign(x)
      sign = Tensor.create(src.to_a.map { |v| v >= 0 ? 1.0 : -1.0 }, src.shape)
      src.agregar_gradiente(g * sign)
    }
  end
  r
end

#add_scalar(s) ⇒ Object



181
182
183
184
185
186
187
188
189
# File 'lib/grx/tensor.rb', line 181

def add_scalar(s)
  r = _unary_c(:grx_add_scalar, s) { |v| v + s }
  if requires_grad
    r.requires_grad = true; r._grafo_hijos << self
    src = self
    r.backward_fn = ->(g) { src.agregar_gradiente(g) }
  end
  r
end

#agregar_gradiente(g) ⇒ Object


AUTOGRAD



487
488
489
# File 'lib/grx/tensor.rb', line 487

def agregar_gradiente(g)
  @grad = @grad.nil? ? g : @grad + g
end

#backward(grad_inicial = nil) ⇒ Object



491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
# File 'lib/grx/tensor.rb', line 491

def backward(grad_inicial = nil)
  if grad_inicial.nil? && @grad.nil?
    agregar_gradiente(Tensor.ones(@shape))
  elsif !grad_inicial.nil?
    agregar_gradiente(grad_inicial)
  end

  # Topological sorting via iterative post-order DFS (prevents stack overflow on deep graphs)
  orden     = []
  visitados = {}
  stack     = [[self, false]]

  until stack.empty?
    nodo, procesado = stack.pop
    if procesado
      orden << nodo unless visitados[nodo.object_id]
      visitados[nodo.object_id] = true
    else
      next if visitados[nodo.object_id]
      stack.push([nodo, true])
      nodo._grafo_hijos.each { |h| stack.push([h, false]) unless visitados[h.object_id] }
    end
  end

  # Topological order in post-order: reverse traverses root first down to leaves
  orden.reverse_each do |nodo|
    next unless nodo.grad && nodo.backward_fn
    nodo.backward_fn.call(nodo.grad)
    nodo.backward_fn = nil
  end
end

#clip(lo, hi) ⇒ Object



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/grx/tensor.rb', line 274

def clip(lo, hi)
  out = _alloc_storage(numel)
  if CAPI::LOADED
    CAPI.grx_clip(@storage.ptr, lo.to_f, hi.to_f, out.ptr, numel)
  else
    data = to_a.map { |v| v < lo ? lo : (v > hi ? hi : v) }
    return Tensor.create(data, @shape, requires_grad: @requires_grad)
  end
  r = Tensor.new(out, @shape)
  if @requires_grad
    r.requires_grad = true; r._grafo_hijos << self
    src = self; l = lo.to_f; h = hi.to_f
    r.backward_fn = ->(g) {
      mask = Tensor.create(src.to_a.map { |v| (v >= l && v <= h) ? 1.0 : 0.0 }, src.shape)
      src.agregar_gradiente(g * mask)
    }
  end
  r
end

#coerce(other) ⇒ Object


SCALAR OPERATIONS



161
162
163
164
165
166
167
168
169
# File 'lib/grx/tensor.rb', line 161

def coerce(other)
  case other
  when Numeric
    # Returns reversed [self, other] wrapper to enable 2.0 * tensor
    [Tensor.new(Storage.new(Array.new(numel, other.to_f)), @shape), self]
  else
    raise TypeError, "#{self.class} cannot be coerced with #{other.class}"
  end
end

#contiguousObject



541
542
543
544
545
546
547
548
549
550
# File 'lib/grx/tensor.rb', line 541

def contiguous
  return self if _contiguous?
  c = Tensor.create(to_a, @shape, requires_grad: @requires_grad)
  if @requires_grad
    c._grafo_hijos << self
    src = self
    c.backward_fn = ->(g) { src.agregar_gradiente(g) }
  end
  c
end

#contiguous?Boolean Also known as: _contiguous?

A tensor is contiguous if its strides match standard row-major order

Returns:

  • (Boolean)


628
629
630
631
# File 'lib/grx/tensor.rb', line 628

def contiguous?
  expected = _calc_strides(@shape)
  @strides == expected && @offset == 0
end

#dot(other) ⇒ Object


LINEAR ALGEBRA

Raises:



352
353
354
355
356
357
358
359
# File 'lib/grx/tensor.rb', line 352

def dot(other)
  raise ShapeError, "dot requires matching shape" if @shape != other.shape
  if CAPI::LOADED
    CAPI.grx_dot(@storage.ptr, other.storage.ptr, numel)
  else
    to_a.zip(other.to_a).sum { |a, b| a * b }
  end
end

#expObject



252
253
254
255
256
257
258
259
260
# File 'lib/grx/tensor.rb', line 252

def exp
  r = _unary_c(:grx_exp) { |v| Math.exp(v) }
  if requires_grad
    r.requires_grad = true; r._grafo_hijos << self
    res = r; src = self
    r.backward_fn = ->(g) { src.agregar_gradiente(g * res) }
  end
  r
end

#flattenObject



605
606
607
# File 'lib/grx/tensor.rb', line 605

def flatten
  reshape([numel])
end

#get(*coords) ⇒ Object


GEOMETRY (zero-copy)



537
538
539
# File 'lib/grx/tensor.rb', line 537

def get(*coords)
  @storage.read(_calc_flat_index(coords))
end

#itemObject



661
662
663
664
# File 'lib/grx/tensor.rb', line 661

def item
  raise "item() only supported for 1-element tensors" if numel != 1
  to_a[0]
end

#leaky_relu(alpha = 0.01) ⇒ Object



406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/grx/tensor.rb', line 406

def leaky_relu(alpha = 0.01)
  r = _unary_c(:grx_leaky_relu, alpha.to_f) { |v| v > 0 ? v : alpha * v }
  if requires_grad
    r.requires_grad = true; r._grafo_hijos << self
    src = self
    r.backward_fn = ->(g) {
      mask = Tensor.create(src.to_a.map { |v| v > 0 ? 1.0 : alpha }, src.shape)
      src.agregar_gradiente(g * mask)
    }
  end
  r
end

#logObject



242
243
244
245
246
247
248
249
250
# File 'lib/grx/tensor.rb', line 242

def log
  r = _unary_c(:grx_log) { |v| Math.log(v) }
  if requires_grad
    r.requires_grad = true; r._grafo_hijos << self
    src = self
    r.backward_fn = ->(g) { src.agregar_gradiente(g / src) }
  end
  r
end

#matmul(other) ⇒ Object

Raises:



361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'lib/grx/tensor.rb', line 361

def matmul(other)
  raise DimensionError, "matmul requires 2D tensors" unless @shape.size == 2 && other.shape.size == 2
  m, k = @shape; k2, n = other.shape
  raise ShapeError, "Incompatible dimensions: #{@shape} × #{other.shape}" if k != k2
  out = _alloc_storage(m * n)
  if CAPI::LOADED
    CAPI.grx_matmul(@storage.ptr, other.storage.ptr, out.ptr, m, k, n)
  else
    result = Array.new(m * n, 0.0)
    m.times { |i| k.times { |kk| aik = @storage.read(i*k+kk)
      n.times { |j| result[i*n+j] += aik * other.storage.read(kk*n+j) } } }
    return Tensor.create(result, [m, n])
  end
  r = Tensor.new(out, [m, n])
  if requires_grad || other.requires_grad
    r.requires_grad = true
    a, b = self, other
    r._grafo_hijos.push(a, b)
    r.backward_fn = ->(g) {
      # dL/dA = dL/dC × B^T,  dL/dB = A^T × dL/dC
      # Uses _matmul_no_grad and _transpose_view to avoid graph recursion
      a.agregar_gradiente(g._matmul_no_grad(b._transpose_view)) if a.requires_grad
      b.agregar_gradiente(a._transpose_view._matmul_no_grad(g)) if b.requires_grad
    }
  end
  r
end

#maxObject



332
333
334
335
336
337
338
# File 'lib/grx/tensor.rb', line 332

def max
  if CAPI::LOADED
    CAPI.grx_max(@storage.ptr, numel)
  else
    to_a.max
  end
end

#meanObject



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/grx/tensor.rb', line 315

def mean
  val = if CAPI::LOADED
    CAPI.grx_mean(@storage.ptr, numel)
  else
    to_a.sum.to_f / numel
  end
  r = Tensor.create([val], [1], requires_grad: @requires_grad)
  if @requires_grad
    r._grafo_hijos << self
    src = self; n = numel.to_f
    r.backward_fn = ->(g) {
      src.agregar_gradiente(Tensor.create(Array.new(src.numel, g.item / n), src.shape))
    }
  end
  r
end

#minObject



340
341
342
343
344
345
346
# File 'lib/grx/tensor.rb', line 340

def min
  if CAPI::LOADED
    CAPI.grx_min(@storage.ptr, numel)
  else
    to_a.min
  end
end

#nan?Boolean

Returns:

  • (Boolean)


676
677
678
679
# File 'lib/grx/tensor.rb', line 676

def nan?
  raise "nan? only supported for 1-element tensors" if numel != 1
  to_a[0].nan?
end

#negateObject



191
192
193
194
195
196
197
198
199
# File 'lib/grx/tensor.rb', line 191

def negate
  r = _unary_c(:grx_negate) { |v| -v }
  if requires_grad
    r.requires_grad = true; r._grafo_hijos << self
    src = self
    r.backward_fn = ->(g) { src.agregar_gradiente(g.negate) }
  end
  r
end

#numelObject


UTILITIES



613
614
615
# File 'lib/grx/tensor.rb', line 613

def numel
  @shape.reduce(1, :*)
end

#pow(e) ⇒ Object



262
263
264
265
266
267
268
269
270
271
272
# File 'lib/grx/tensor.rb', line 262

def pow(e)
  r = _unary_c(:grx_pow, e.to_f) { |v| v ** e }
  if requires_grad
    r.requires_grad = true; r._grafo_hijos << self
    src = self
    r.backward_fn = ->(g) {
      src.agregar_gradiente(g * src.pow(e - 1).scale(e.to_f))
    }
  end
  r
end

#reluObject


ACTIVATIONS (with autograd)



393
394
395
396
397
398
399
400
401
402
403
404
# File 'lib/grx/tensor.rb', line 393

def relu
  r = _unary_c(:grx_relu) { |v| v > 0 ? v : 0.0 }
  if requires_grad
    r.requires_grad = true; r._grafo_hijos << self
    src = self
    r.backward_fn = ->(g) {
      mask = Tensor.create(src.to_a.map { |v| v > 0 ? 1.0 : 0.0 }, src.shape)
      src.agregar_gradiente(g * mask)
    }
  end
  r
end

#reshape(nueva_forma) ⇒ Object

Raises:

  • (ArgumentError)


552
553
554
555
556
557
558
559
560
561
# File 'lib/grx/tensor.rb', line 552

def reshape(nueva_forma)
  raise ArgumentError, "Incompatible reshape" if numel != nueva_forma.reduce(1,:*)
  r = Tensor.new(@storage, nueva_forma, offset: @offset, requires_grad: @requires_grad)
  if @requires_grad
    r._grafo_hijos << self
    src = self; orig_shape = @shape
    r.backward_fn = ->(g) { src.agregar_gradiente(g.reshape(orig_shape)) }
  end
  r
end

#scale(s) ⇒ Object



171
172
173
174
175
176
177
178
179
# File 'lib/grx/tensor.rb', line 171

def scale(s)
  r = _unary_c(:grx_scale, s) { |v| v * s }
  if requires_grad
    r.requires_grad = true; r._grafo_hijos << self
    src = self; factor = s.to_f
    r.backward_fn = ->(g) { src.agregar_gradiente(g.scale(factor)) }
  end
  r
end

#sigmoidObject



432
433
434
435
436
437
438
439
440
441
442
443
# File 'lib/grx/tensor.rb', line 432

def sigmoid
  r = _unary_c(:grx_sigmoid) { |v| 1.0 / (1.0 + Math.exp(-v)) }
  if requires_grad
    r.requires_grad = true; r._grafo_hijos << self
    res = r; src = self
    r.backward_fn = ->(g) {
      # d(sigmoid)/dx = sigmoid * (1 - sigmoid)
      src.agregar_gradiente(g * res * (Tensor.ones_like(res) - res))
    }
  end
  r
end

#softmaxObject



445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
# File 'lib/grx/tensor.rb', line 445

def softmax
  dim = @shape[-1]
  batch = numel / dim
  raw = to_a
  out_vals = Array.new(numel)

  batch.times do |b|
    slice = raw.slice(b * dim, dim)
    max_v = slice.max
    exps = slice.map { |v| Math.exp(v - max_v) }
    sum_e = exps.sum
    dim.times { |j| out_vals[b * dim + j] = exps[j] / sum_e }
  end

  r = Tensor.create(out_vals, @shape, requires_grad: @requires_grad)
  if @requires_grad
    r._grafo_hijos << self
    res = r; src = self
    r.backward_fn = ->(g) {
      s_data = res.to_a
      g_data = g.to_a
      grad_x = Array.new(src.numel, 0.0)

      batch.times do |b|
        s_row = s_data.slice(b * dim, dim)
        g_row = g_data.slice(b * dim, dim)
        dot = s_row.zip(g_row).sum { |s_val, g_val| s_val * g_val }
        dim.times do |j|
          grad_x[b * dim + j] = s_row[j] * (g_row[j] - dot)
        end
      end

      src.agregar_gradiente(Tensor.create(grad_x, src.shape))
    }
  end
  r
end

#sqrtObject



219
220
221
222
223
224
225
226
227
228
229
230
# File 'lib/grx/tensor.rb', line 219

def sqrt
  r = _unary_c(:grx_sqrt) { |v| Math.sqrt(v) }
  if requires_grad
    r.requires_grad = true; r._grafo_hijos << self
    res = r; src = self
    r.backward_fn = ->(g) {
      # d(sqrt(x))/dx = 1 / (2*sqrt(x))
      src.agregar_gradiente(g / (res.scale(2.0)))
    }
  end
  r
end

#squareObject



232
233
234
235
236
237
238
239
240
# File 'lib/grx/tensor.rb', line 232

def square
  r = _unary_c(:grx_square) { |v| v * v }
  if requires_grad
    r.requires_grad = true; r._grafo_hijos << self
    src = self
    r.backward_fn = ->(g) { src.agregar_gradiente(g * src.scale(2.0)) }
  end
  r
end

#sumObject


REDUCTIONS (return differentiable scalar Tensor with autograd)



298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/grx/tensor.rb', line 298

def sum
  val = if CAPI::LOADED
    CAPI.grx_sum(@storage.ptr, numel)
  else
    to_a.sum
  end
  r = Tensor.create([val], [1], requires_grad: @requires_grad)
  if @requires_grad
    r._grafo_hijos << self
    src = self
    r.backward_fn = ->(g) {
      src.agregar_gradiente(Tensor.create(Array.new(src.numel, g.item), src.shape))
    }
  end
  r
end

#tanhObject



419
420
421
422
423
424
425
426
427
428
429
430
# File 'lib/grx/tensor.rb', line 419

def tanh
  r = _unary_c(:grx_tanh_act) { |v| Math.tanh(v) }
  if requires_grad
    r.requires_grad = true; r._grafo_hijos << self
    res = r; src = self
    r.backward_fn = ->(g) {
      # d(tanh)/dx = 1 - tanh(x)^2
      src.agregar_gradiente(g * (Tensor.ones_like(res) - res.square))
    }
  end
  r
end

#to_aObject



617
618
619
620
621
622
623
624
625
# File 'lib/grx/tensor.rb', line 617

def to_a
  # If strides are contiguous (normal tensor, reshape), read buffer directly.
  # Otherwise (transpose, strided views), traverse with custom strides.
  if _contiguous?
    @storage.to_ruby_array
  else
    _collect_elements(@shape, @strides, @offset)
  end
end

#to_fObject



666
667
668
669
# File 'lib/grx/tensor.rb', line 666

def to_f
  raise "to_f only supported for 1-element tensors" if numel != 1
  to_a[0]
end

#to_iObject



671
672
673
674
# File 'lib/grx/tensor.rb', line 671

def to_i
  raise "to_i only supported for 1-element tensors" if numel != 1
  to_a[0].to_i
end

#to_sObject Also known as: inspect



681
682
683
# File 'lib/grx/tensor.rb', line 681

def to_s
  "#<GRX::Tensor shape=#{@shape} data=#{to_a}>"
end

#transposeObject

Raises:



563
564
565
566
567
568
569
570
571
572
573
574
575
576
# File 'lib/grx/tensor.rb', line 563

def transpose
  raise DimensionError, "transpose only supports 2D tensors" if @shape.size != 2
  t = Tensor.new(@storage, [@shape[1], @shape[0]],
             strides: [@strides[1], @strides[0]],
             offset: @offset, requires_grad: @requires_grad)
  if @requires_grad
    t._grafo_hijos << self
    src = self
    t.backward_fn = ->(g) {
      src.agregar_gradiente(g.transpose)
    }
  end
  t
end

#zero_grad!Object



523
524
525
526
527
# File 'lib/grx/tensor.rb', line 523

def zero_grad!
  @grad = nil
  @_grafo_hijos = []
  @backward_fn = nil
end