Skip to content

Elementwise

Elementwise ops operate on a per element basis. They don't change the shape of the tensor.

Unary Ops (math)¤

exp ¤

exp()

Elementwise e ** x.

Source code in stackgrad/tensor.py
313
314
315
def exp(self):
  """Elementwise `e ** x`."""
  return _apply(mlops.Exp, self)

log ¤

log()
Source code in stackgrad/tensor.py
317
318
def log(self):
  return _apply(mlops.Log, self)

recip ¤

recip()
Source code in stackgrad/tensor.py
320
321
def recip(self):
  return _apply(mlops.Recip, self)

abs ¤

abs()
Source code in stackgrad/tensor.py
332
333
def abs(self):
  return where(self < 0, -self, self)

clamp ¤

clamp(min_val=None, max_val=None)
Source code in stackgrad/tensor.py
335
336
337
338
339
340
341
def clamp(self, min_val=None, max_val=None):
  out = self
  if min_val is not None:
    out = where(out < min_val, min_val, out)
  if max_val is not None:
    out = where(out > max_val, max_val, out)
  return out

cast ¤

cast(dtype)

Convert to dtype ("float32", "bfloat16", ...); the gradient comes back in the old dtype.

Source code in stackgrad/tensor.py
309
310
311
def cast(self, dtype):
  """Convert to `dtype` ("float32", "bfloat16", ...); the gradient comes back in the old dtype."""
  return _apply(mlops.Cast, self, dtype=backend.get(self.device).dtype(dtype))

Unary Ops (activation)¤

relu ¤

relu()
Source code in stackgrad/tensor.py
326
327
def relu(self):
  return where(self > 0, self, 0.0)

sigmoid ¤

sigmoid()
Source code in stackgrad/tensor.py
323
324
def sigmoid(self):
  return _apply(mlops.Sigmoid, self)

tanh ¤

tanh()
Source code in stackgrad/tensor.py
329
330
def tanh(self):
  return 2.0 * (2.0 * self).sigmoid() - 1.0

Ternary Ops¤

where ¤

where(cond, x, y)

Elementwise x if cond else y. cond is a mask and gets no gradient.

Source code in stackgrad/tensor.py
408
409
410
411
412
413
def where(cond, x, y):
  """Elementwise `x if cond else y`. `cond` is a mask and gets no gradient."""
  ref = x if isinstance(x, Tensor) else y
  cond = cond if isinstance(cond, Tensor) else Tensor(backend.get(ref.device).asarray(cond), device=ref.device)
  x, y = _broadcast([ref._const(x), ref._const(y)], cond.shape)
  return _apply(mlops.Where, x, y, cond)