Skip to content

Reduce and Autograd

Reduce¤

sum ¤

sum(axis=None, keepdims=False)

Sum over axis, or over every element when axis is None.

Source code in stackgrad/tensor.py
253
254
255
def sum(self, axis=None, keepdims=False):
  """Sum over `axis`, or over every element when `axis` is None."""
  return _apply(mlops.Sum, self, axis=axis, keepdims=keepdims)

mean ¤

mean(axis=None, keepdims=False)

Mean over axis, or over every element when axis is None.

Source code in stackgrad/tensor.py
257
258
259
260
261
def mean(self, axis=None, keepdims=False):
  """Mean over `axis`, or over every element when `axis` is None."""
  out = self.sum(axis=axis, keepdims=keepdims)
  # from shapes, not .data, so the graph stays lazy
  return out * (math.prod(out.shape) / math.prod(self.shape))

max ¤

max(axis=None, keepdims=False)
Source code in stackgrad/tensor.py
263
264
def max(self, axis=None, keepdims=False):
  return _apply(mlops.Max, self, axis=axis, keepdims=keepdims)

min ¤

min(axis=None, keepdims=False)
Source code in stackgrad/tensor.py
266
267
def min(self, axis=None, keepdims=False):
  return -((-self).max(axis=axis, keepdims=keepdims))

Autograd¤

backward ¤

backward(keep_grads=False)

Backpropagate from this scalar, filling .grad on every leaf (and intermediates if keep_grads).

Source code in stackgrad/tensor.py
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
def backward(self, keep_grads=False):
  """Backpropagate from this scalar, filling `.grad` on every leaf (and intermediates if `keep_grads`)."""
  assert self.data.size == 1, "backward() only works on scalar tensors - call .sum() or .mean() first"
  assert self.requires_grad, "nothing this tensor depends on has requires_grad=True, so backward() has no gradients to compute"

  # iterative, so a deep graph cannot hit the recursion limit
  topo, visited, stack = [], set(), [(self, False)]
  while stack:
    node, processed = stack.pop()
    if processed:
      topo.append(node)
    elif node not in visited:
      visited.add(node)
      stack.append((node, True))
      stack.extend((p, False) for p in (node._ctx.parents if node._ctx else ()) if p.requires_grad)

  self.grad = backend.get(self.device).ones_like(self.data)
  for node in reversed(topo):
    if node._ctx is None or node.grad is None:
      continue
    if _profiler is None:
      grads = node._ctx.backward(node.grad)
    else:
      grads = _profiler.time(type(node._ctx).__name__ + " backward", node.device, node._ctx.backward, node.grad)
    # free intermediate grads once passed on, so a second backward() starts clean
    if not keep_grads:
      node.grad = None
    for parent, grad in zip(node._ctx.parents, grads):
      if grad is not None and parent.requires_grad:
        # never +=: Add hands one grad array to both parents
        parent.grad = grad if parent.grad is None else parent.grad + grad

zero_grad ¤

zero_grad()
Source code in stackgrad/tensor.py
375
376
def zero_grad(self):
  self.grad = None

no_grad ¤

Context manager to disable gradient tracking during inference.

autocast ¤

autocast(dtype)

Mixed precision: every Linear multiplies in dtype ("bfloat16" or "float16"), all else stays float32.

Source code in stackgrad/tensor.py
31
32
def __init__(self, dtype):
  self.dtype = dtype