Implementing kernel
C++ engine symbols that back this Python API.One-hot encode an integer class index tensor.
Maps each integer entry into a one-hot vector along a new trailing
axis of size num_classes:
Parameters
inputTensorint64 tensor of arbitrary shape (*) whose entries are class
indices in [0, num_classes). Any other dtype is refused, as the
reference framework does -- cast with input.long().num_ classesint= -1Total number of classes . If
-1 (the default), it
is inferred as input.max() + 1; supplying an explicit value
avoids a host round-trip and is preferred in hot loops.Returns
TensorOne-hot encoded int64 tensor of shape (*, num_classes).
Cast to a floating dtype if it will participate in gradient-based
computation.
Raises
ValueErrorIf
num_classes is -1 and input is empty — there is no
largest index to infer the count from — or if num_classes is
otherwise not positive.IndexErrorIf a CPU
input holds a class outside [0, num_classes),
a negative one included; it used to give a row of zeros. A Metal
input is not read back for the check (that would stall every
step), and a class outside the range gives a row of zeros there,
unless LUCID_STRICT_INDEX=1 is set, which raises on Metal too.Notes
For loss functions like cross-entropy, prefer passing raw integer targets to the loss directly — one-hot encoding then immediately contracting against a softmax wastes memory and breaks the log-sum-exp fused path.
Examples
>>> import lucid
>>> from lucid.nn.functional import one_hot
>>> idx = lucid.tensor([0, 2, 1, 2], dtype=lucid.int64)
>>> one_hot(idx, num_classes=3)
tensor([[1, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 0, 1]], dtype=lucid.int64)
>>> one_hot(lucid.tensor([1, 0])) # num_classes inferred as max + 1
tensor([[0, 1],
[1, 0]], dtype=lucid.int64)