Define Tensor: The Data Structure Behind Visual RAG, with Examples

Define tensor as shape, dtype and device, then follow one product image through visual RAG to see how dimension, precision and batching set cost.

Define Tensor: The Data Structure Behind Visual RAG, with Examples
Written by TechnoLynx Published on 11 Jul 2026

If you need to define tensor for machine learning, the working definition is short: a tensor is a multidimensional array of numbers with three pieces of metadata, namely a shape (a tuple of axis lengths), a dtype (the numeric type of each element) and a device (CPU, GPU or TPU). PyTorch describes its tensors the same way and uses them for a model’s inputs, outputs and parameters alike. That definition sounds abstract until you follow one product photo through a visual retrieval-augmented generation (visual RAG) pipeline. The photo becomes an image tensor, then an embedding vector, then an entry in an index. At catalogue scale, the embedding’s dimension directly sets the index’s storage footprint and retrieval cost.

Define Tensor by Its Three Attributes, Shown in Code

The shape is a tuple of axis lengths: how many axes there are and how long each one is. The dtype tells you how many bytes each element costs: float32 takes 4 bytes, bfloat16 and float16 take 2, int8 takes 1 and int4 takes half a byte. The device tells you where the data is stored. Operations between tensors on different devices raise an error, so you cannot multiply a CPU tensor against a CUDA tensor.

import torch

x = torch.rand(3, 224, 224)          # one RGB image-sized tensor
print(x.shape)    # torch.Size([3, 224, 224])
print(x.dtype)    # torch.float32
print(x.device)   # cpu

x = x.to("cuda")                      # explicit move to the accelerator
print(x.device)   # cuda:0

PyTorch creates tensors on the CPU by default, and you have to move them to an accelerator explicitly with .to. Copying large tensors across devices costs both time and memory. Under the hood, a tensor’s data sits in a flat one-dimensional buffer. The shape plus the strides (how many elements to step to advance one position along each axis) map multidimensional indexing onto that buffer. This matters more than it looks. permute, transpose and slicing produce non-contiguous tensors without copying anything, and many CUDA kernels either fall back to slower paths or error out on non-contiguous inputs.

A matrix is simply the two-dimensional case, and a vector is the one-dimensional case. For more worked shapes and their quirks, our page of tensor examples in visual search goes further into how image tensors drive product matching.

How Is a Product Image Turned into a Tensor Before a Visual Search Model Can Use It?

A decoded product photo is converted into a tensor of shape (C, H, W), where C is the number of channels and H and W are height and width. A batch of images becomes a (B, C, H, W) tensor, with B the number of images. The standard torchvision conversion takes a PIL image or NumPy array laid out as H × W × C, with values from 0 to 255, and returns a float tensor of shape C × H × W with values from 0.0 to 1.0. The value range follows the dtype: torchvision expects float image tensors to sit in [0, 1) and integer image tensors in [0, the dtype’s maximum].

The same sequence shows up outside PyTorch. One 2026 medical-imaging study using TensorFlow converted its image tensors from uint8 to float32 first, so that scaling would be straightforward, and then normalised the RGB values from 0–255 down to 0–1.

from PIL import Image
import torchvision.transforms as T

img = Image.open("sku_10482_front.jpg").convert("RGB")   # H x W x C, uint8
to_tensor = T.Compose([T.Resize((224, 224)), T.ToTensor()])
t = to_tensor(img)            # (3, 224, 224), float32, values in [0, 1]
batch = t.unsqueeze(0)        # (1, 3, 224, 224): the batch axis the encoder expects

A single image still needs the batch axis, because encoders are written to process (B, C, H, W) input.

What an Image Embedding Tensor Looks Like Inside a Product Index

The encoder turns that (1, 3, 224, 224) input into one dense vector per image. In CLIP, the image tower (a ViT-L/14, or a ViT-B/32 in smaller variants) produces a 768-dimensional vector. The text tower produces a vector of the same size, and both are projected into a shared 512-dimensional space and L2-normalised. Stack the whole catalogue and you get a two-dimensional (N, 512) tensor, where N is the number of product images.

The index is where those stored embeddings get searched against a query. In a worked CLIP and FAISS example, every image embedding is stored in a FAISS index. A “Flat” index compares the query against every stored vector by brute force, which returns exact results at the price of more computation. At query time, the query embedding is cast to float32 and reshaped to a single row before the search call. Retrieval scores are inner products between the query embedding and each stored embedding, and maximum inner product search returns the top-k candidates sorted by that score. On L2-normalised vectors such as CLIP’s, the inner product equals cosine similarity.

In a product-image retrieval paper, Stanley and colleagues describe a typical embedding as a high-dimensional floating-point vector. Both the high dimensionality and the many floating-point comparisons hinder scalable, near-real-time search. For the wider history of searching by image content, see our article on content-based image retrieval with computer vision.

How Visual RAG Uses Image and Text Tensors to Retrieve and Describe Products

Visual RAG with text queries needs images and text in the same vector space. CLIP is a dual-encoder model that embeds both images and text into one shared vector space. That means a shopper’s text query can be embedded and matched against the nearest image embeddings. RAG then has two phases: retrieve contextually relevant information, then guide generation with what was retrieved. In visual RAG, the first phase returns product images and their metadata, and the second hands them to a multimodal generator that writes the answer or the product description.

RAVEN shows the mechanics. It uses the off-the-shelf CLIP image encoder for both the query and the memory, indexes the memory with FAISS, runs top-50 retrieval, and keeps the top image along with its captions and alt text for the generator. The Visual-RAG benchmark (Wu et al., 2025) found that retrieved images provide strong evidence for generation. Even so, the models it tested struggled to extract and use that visual knowledge efficiently.

Two cautions apply when you combine modalities. After training, CLIP’s image embeddings and text embeddings sit in separate cones of the unit sphere. They are closer to their cross-modal matches than to random negatives, but the two modalities never fully interleave. We would therefore calibrate text-to-image and image-to-image scores before merging them into one ranked list. The payoff from using both can be real, though. In the 2020 e-commerce study, image-based candidates gave 13% higher recall than text alone, and combining the two raised recall by 24%.

The retrieval and generation design choices are covered in visual RAG for product discovery. The broader patterns are in our guide to retrieval augmented generation examples and guidance.

Why Tensor Size and Embedding Dimensionality Drive Visual Search Cost at Catalogue Scale

Index storage is plain tensor arithmetic: number of vectors × dimensions × bytes per dimension. A 2025 study of RAG embedding storage writes it as N × (original dimensions × PCA ratio) × bytes per dimension. The embedding dimension directly sets both the index’s storage footprint and the compute cost of retrieval. Scoring costs roughly one multiply-add per dimension per document scored. So a flat search over N products at dimension D does about N × D multiply-adds per query.

Worked Example: One Million Product Images at CLIP’s 512 Dimensions

Assumptions: 1,000,000 catalogue images, one 512-dimensional CLIP embedding each. The figures count raw vectors only, excluding index structures and metadata.

Stored dtype Bytes per vector Raw index size Reduction vs float32
float32 512 × 4 = 2,048 ≈ 2.05 GB 1×
float16 512 × 2 = 1,024 ≈ 1.02 GB 2×
int8 512 × 1 = 512 ≈ 0.51 GB 4×
binary (1 bit, packed) 512 ÷ 8 = 64 ≈ 0.06 GB 32×

The ratios match the published ones: float16 halves storage, int8 cuts it by four, and binary quantisation to 1-bit values cuts memory and storage by 32. The same 2025 study gives a 1536-dimensional float32 vector as 6 KB, and either int8 at 1536 dimensions or float32 at 384 dimensions as 1.5 KB. One million such 1536-dimensional float32 vectors need about 6.1 GB of RAM before any index overhead. Hugging Face (2024) puts retrieval over 250 million 1024-dimensional float32 vectors at roughly 1 TB of memory.

A higher dimension buys accuracy, but each extra dimension buys less. A study of scaling laws for embedding dimension found consistent but diminishing returns as dimension grows. The same authors found that a larger model with a smaller embedding dimension often matches the quality of a smaller model with a larger one, while potentially halving the index. An evaluation of RAG text-search pipelines reported Top-3 accuracy of 0.571 at 4096 dimensions against 0.412 at 1024. It also noted that storage scales linearly with dimension and that search latency rises with it. Both studies measured text retrieval, not product images. Treat their curves as the shape of the trade-off, and measure your own catalogue for the actual numbers.

How Batching and Precision (FP32, FP16, INT8) Affect Product-Image Matching

Precision enters a visual search system in two places, and the decision differs in each.

On the encoder side, lower precision means higher throughput. The DEEP-GAP benchmark ran ResNet image models on NVIDIA T4 and L4 GPUs in FP32 (PyTorch CUDA), FP16 (mixed precision) and INT8 (TensorRT). INT8 consistently gave the lowest latency, FP16 came in between and FP32 was slowest. INT8 also cut GPU memory in those ResNet runs by roughly 2–3× compared with FP32. Accuracy is the cost. NVIDIA’s TensorRT documentation says higher-precision layers generally help accuracy at some performance cost. It also says FP16 may need retraining to avoid overflow or underflow, and INT8 may need recalibration on a more representative dataset. In a transformer study, running everything in FP16 cost 0.34 accuracy points on SST-2. A hybrid that kept softmax and layer normalisation in FP32 matched the FP32 baseline exactly.

On the index side, quantising the stored embeddings trades some retrieval quality for memory and speed. Hugging Face reports an average 3.66× retrieval speedup for int8 embeddings over float32. With a rescore multiplier of 4–5, int8 retained 99% of performance. The same storage study measured a 1.5–3.5% drop for int8, which also needs a calibration dataset. Float8 gave the same 4× reduction with under 0.3% degradation. For product images specifically, the 2020 e-commerce study cut mean query time by 70% by moving VGG16 embeddings to 256 subcodes, with less than 2% loss in precision and recall.

Batching follows a different curve. In DEEP-GAP, throughput rose quickly as the batch grew from 1 to 32, then plateaued as compute or memory bandwidth saturated. Latency grew roughly linearly with batch size. NVIDIA’s documentation says the same thing: larger batches improve throughput by spreading launch overhead across more work, but they raise latency and memory use and are not universally faster. Tensor shape matters here too. Tensor Core layers perform better when I/O dimensions are aligned, with a suggested alignment of 8 elements for dense FP16 math. When dimensions are not aligned, TensorRT can pad them, and padding adds computation and memory traffic.

Which Lever to Pull, by Goal

Goal Lever What it costs Check before shipping
Faster catalogue re-embedding (offline) Larger encoder batch, FP16 or INT8 encoder Memory per batch; possible accuracy drift from INT8 calibration Embedding similarity to FP32 outputs on a sample of SKUs
Low-latency query encoding (shopper-facing) Small batch, reduced precision Lower GPU utilisation per call Tail latency at realistic concurrency
Smaller index in memory float16, float8, int8 or binary embeddings; lower dimension Recall loss, larger for more aggressive compression Recall@k on real catalogue queries, with and without rescoring
Faster search at very large N Approximate index or compressed codes instead of a flat index Approximation error Recall against an exact flat-index baseline

The table is our judgement, drawn from the measured effects above.

Measuring Recall Loss on Your Own Catalogue Before Shrinking the Index

The published trade-offs above come from other data: ResNet classifiers, transformer text tasks, text retrieval benchmarks and one retailer’s VGG16 embeddings. None of them tells you how many of your own shoppers’ visual queries will lose the right product when you halve the dimension or switch to int8. We would build the exact flat-index baseline first. Then we would compare each compression step against it on queries from real search logs, since sensitivity to compression varies by model. In the 2025 storage study, a 768-dimensional model lost 6.9% when kept at 25% of its dimensions, while a 384-dimensional model lost 19.6%.

TechnoLynx’s Computer Vision R&D builds and deploys computer vision systems such as this encoder-to-index pipeline. TechnoLynx’s Generative & Agentic AI R&D covers the generator that reads the retrieved images. The open question for any retail team is not whether compression shrinks the index, because the arithmetic already shows it does. The question is how much recall on your own long-tail products you are willing to give up for each gigabyte you save.