Tensor Slicing: Extract Mini-Batch & Last Feature Column

Basics
BasicsPyTorchIndexingGoogleMetaAmazon

Problem

Given a 2D feature matrix X of shape (N, D) and an integer batch_size, implement slice_batch_and_col(X, batch_size) to return (mini_batch, last_col) where mini_batch = X[:batch_size] contains the first batch_size rows and last_col = X[:, -1] extracts the final feature column across all N rows.

Why It Matters: Mini-batch training loops slice datasets into (B, D) chunks, while target extraction and autoregressive last-token pooling rely on negative-index slicing like [:, -1].

Function Signature

import torch

def slice_batch_and_col(X: torch.Tensor, batch_size: int):
    """Return (first batch_size rows of X, last column of X)."""

Sample Input & Output

Example 1: First 2 Rows & Last Column

Input:

X = torch.tensor([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]), batch_size = 2

Expected Output:

mini_batch = tensor([[1., 2., 3.], [4., 5., 6.]])
last_col = tensor([3., 6., 9.])

Explanation: X[:2] selects rows 0 and 1 with shape (2, 3); X[:, -1] returns the 1D last column of shape (3,).

Example 2: batch_size Larger Than N

Input:

X = torch.tensor([[10., 20.], [30., 40.]]), batch_size = 5

Expected Output:

mini_batch = tensor([[10., 20.], [30., 40.]])
last_col = tensor([20., 40.])

Explanation: PyTorch slicing safely caps at N = 2 without raising an IndexError when batch_size > N.

Constraints & Edge Cases

  • Return (first_batch, last_col).
  • last_col must be a 1D tensor of shape (N,), not (N, 1).
  • Do not mutate X in place.

Constraints & Evaluation Criteria

  • Return `(first_batch, last_col)`.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
3x2 tensor, batch_size=2
Expected Output / Criteria
batch (2,2), last_col [2,4,6]