Skip to main content

Categorical

Categorical(class_dim=-1, mask_fn=None)

Softmax likelihood over a class axis of \(f\).

At each position, with \(q = \operatorname{softmax}(f)\) over the classes,

\[p(y \mid f) = q_y, \qquad H = \operatorname{diag}(q) - q q^\top,\]

where \(H\) is the output Hessian.

Targets are class indices, shaped like \(f\) without the class axis. log_prob is per position, shaped like the targets. With a mask the class axis must be last.

Parameters

Name Type Description Default
class_dim int The class axis of \(f\). The default is the last axis. -1
mask_fn Callable[[Outputs, Inputs], Tensor | None] | None mask_fn(f, inputs) returns a bool tensor shaped like the targets, False at positions that don’t count (padding, say), or None when every position counts. Without it, every position counts. None

Raises

Name Type Description
StructureError class_dim is 0, the batch axis.

Methods

Name Description
check_targets Raise ValueError unless the targets are integer class indices.
distribution A torch Categorical with logits \(f\), the class axis moved last.
log_prob \(\log q_y\) at each position.
mask mask_fn(f, inputs), or None without mask_fn.
output_hessian \(\operatorname{diag}(q) - q q^\top\) at each position.

check_targets

Categorical.check_targets(y, /)

Raise ValueError unless the targets are integer class indices.

A torch Categorical casts float targets to integers, so 1.7 would count as class 1.

Parameters

Name Type Description Default
y Targets The batch’s targets. required

distribution

Categorical.distribution(f, /)

A torch Categorical with logits \(f\), the class axis moved last.

Parameters

Name Type Description Default
f Outputs Model outputs for a batch. required

Returns

Name Type Description
Distribution A torch distribution over the batch’s targets.

log_prob

Categorical.log_prob(f, y, /)

\(\log q_y\) at each position.

Parameters

Name Type Description Default
f Outputs Model outputs for a batch. required
y Targets Targets for the same batch. required

Returns

Name Type Description
Tensor A tensor shaped [N], or [N, *positions] (per token, say).

Raises

Name Type Description
StructureError y is not shaped like \(f\) without the class axis.

mask

Categorical.mask(f, inputs, /)

mask_fn(f, inputs), or None without mask_fn.

Parameters

Name Type Description Default
f Outputs Model outputs for a batch. required
inputs Inputs The batch’s inputs. required

Returns

Name Type Description
Tensor | None A bool tensor shaped like the output of log_prob, [N, *positions], True where a position counts, or None when every position counts.

output_hessian

Categorical.output_hessian(f, /)

\(\operatorname{diag}(q) - q q^\top\) at each position.

Parameters

Name Type Description Default
f Outputs Model outputs for a batch. required

Returns

Name Type Description
OutputHessian The per-example output Hessian.