Softmax & Argmax Class Prediction on a 2D Batch

Basics
BasicsPyTorchSoftmaxGoogleMetaAmazon

Problem

Given a 2D batch of multi-class logits logits with shape (B, C), implement softmax_predict(logits) returning (probs, pred_classes) where probs applies softmax across the class dimension (dim=-1) so each row sums to 1.0, and pred_classes is the 1D argmax class index for each sample.

Why It Matters: Every multi-class neural network (image classifiers, intent routers, LLM next-token heads) converts a (B, C) logit matrix into row-wise probabilities and predicted class IDs.

Function Signature

import torch

def softmax_predict(logits: torch.Tensor):
    """Return (softmax_probs [B, C], predicted_class_ids [B])."""

Sample Input & Output

Example 1: Batch of 2 Samples Over 3 Classes

Input:

logits = torch.tensor([[2.0, 1.0, 0.0], [0.0, 0.0, 3.0]])

Expected Output:

probs = tensor([[0.6652, 0.2447, 0.0900], [0.0453, 0.0453, 0.9094]])
pred_classes = tensor([0, 2])

Explanation: Row 0 peaks at index 0 (0.6652); Row 1 peaks at index 2 (0.9094). Every row sums to 1.0.

Example 2: Uniform Logits (Tie-Breaking)

Input:

logits = torch.tensor([[1.0, 1.0, 1.0, 1.0]])

Expected Output:

probs = tensor([[0.2500, 0.2500, 0.2500, 0.2500]])
pred_classes = tensor([0])

Explanation: Equal logits produce uniform probabilities 0.25 each; torch.argmax returns the first index 0.

Constraints & Edge Cases

  • Return (probs, preds) for a (B, C) logits tensor.
  • Always specify dim=-1 (not dim=0, which would normalize across the batch instead of classes!).
  • pred_classes must have shape (B,).

Constraints & Evaluation Criteria

  • Return `(probs, preds)` for a `(B, C)` logits tensor.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
[[2,1,0.1],[0.1,3,0.2]]
Expected Output / Criteria
preds=[0, 1]