A JaggedTensor is a specialized data type in TorchRec designed to represent sparse features with variable-length sequences efficiently. Unlike a standard torch.Tensor, which requires padding to make all sequences the same length, a JaggedTensor stores data contiguously without padding, saving memory and computation.
It consists of three key components:
Lengths: A list of integers representing the number of elements for each entity.Offsets: A list of integers representing the starting index of each sequence in the flattened values tensor (an alternative to Lengths).Values: A 1D tensor containing the actual values for each entity, stored contiguously.
# User interactions:
# - User 1 interacted with 2 items
# - User 2 interacted with 3 items
# - User 3 interacted with 1 item
lengths = [2, 3, 1]
offsets = [0, 2, 5] # Starting index of each user's interactions
values = torch.Tensor([101, 102, 201, 202, 203, 301]) # Item IDs interacted with
jt = JaggedTensor(lengths=lengths, values=values)
# OR
jt = JaggedTensor(offsets=offsets, values=values)