🤖 AI/ML

Tensor

Tensor

A multidimensional array. The basic data structure of deep learning. The unit of computation in TensorFlow and PyTorch.

📖 Detailed Explanation

A tensor is a mathematical concept that generalizes the multi-dimensional array, and it is the fundamental data structure of deep learning and scientific computing. It includes scalars (0-dimensional), vectors (1-dimensional), and matrices (2-dimensional), and represents higher-dimensional data of 3 or more dimensions as well. In deep learning frameworks such as PyTorch and TensorFlow, all data and operations are carried out in units of tensors.

The term tensor originally referred, in physics and mathematics, to an object that transforms in a specific way under coordinate transformations. Machine learning borrowed this concept and uses it to represent multi-dimensional arrays of numbers. The term became popular with the emergence of TensorFlow in 2015, and modern deep learning frameworks such as PyTorch, JAX, and MLX have all adopted tensors as their core data structure.

The key attributes of a tensor are shape, data type (dtype), and device. Shape indicates the size of each dimension and is expressed like (batch size, channels, height, width). dtype determines data precision such as float32, float16, and int64, and device specifies the hardware on which operations are performed, such as a CPU or GPU (cuda). Tensor operations support NumPy-like syntax such as broadcasting, indexing, and slicing, while also providing GPU acceleration and automatic differentiation.

In 2024-2025 practice, mixed precision training (FP16/BF16) and quantization (INT8, INT4) became the standard, greatly improving the efficiency of tensor operations. NVIDIA's Tensor Core, Apple's Neural Engine, and Google's TPU are all hardware optimized for tensor operations. In addition, JIT compilers such as Triton and torch.compile() automatically optimize tensor operations to maximize performance.

💻 Code Example

Basic usage of PyTorch tensors.

# PyTorch 텐서 기초
# pip install torch

import torch

# 다양한 방법으로 텐서 생성
zeros = torch.zeros(3, 4)           # 3x4 영행렬
ones = torch.ones(2, 3, 4)          # 2x3x4 일행렬
rand = torch.rand(3, 3)             # 0~1 균등분포
randn = torch.randn(3, 3)           # 표준정규분포
arange = torch.arange(0, 10, 2)     # [0, 2, 4, 6, 8]

# 리스트/NumPy에서 변환
from_list = torch.tensor([[1, 2], [3, 4]])
import numpy as np
from_numpy = torch.from_numpy(np.array([1.0, 2.0, 3.0]))

# 텐서 속성 확인
print(f"Shape: {rand.shape}")       # torch.Size([3, 3])
print(f"Dtype: {rand.dtype}")       # torch.float32
print(f"Device: {rand.device}")     # cpu

# GPU로 이동 (CUDA 사용 가능시)
if torch.cuda.is_available():
    gpu_tensor = rand.to('cuda')
    print(f"GPU Device: {gpu_tensor.device}")  # cuda:0

# 텐서 연산
a = torch.tensor([[1, 2], [3, 4]], dtype=torch.float32)
b = torch.tensor([[5, 6], [7, 8]], dtype=torch.float32)

print(f"덧셈: {a + b}")
print(f"행렬곱: {a @ b}")  # 또는 torch.matmul(a, b)
print(f"요소별 곱: {a * b}")

# 형태 변환
c = torch.arange(12)
print(f"원본: {c.shape}")           # [12]
print(f"reshape: {c.reshape(3, 4).shape}")   # [3, 4]
print(f"view: {c.view(2, 6).shape}")         # [2, 6]
print(f"unsqueeze: {c.unsqueeze(0).shape}")  # [1, 12]

# 자동 미분 (딥러닝의 핵심)
x = torch.tensor([2.0, 3.0], requires_grad=True)
y = x ** 2 + 2 * x + 1
loss = y.sum()
loss.backward()
print(f"기울기 (dy/dx): {x.grad}")  # [6.0, 8.0]

TensorFlow tensors and practical usage examples.

# TensorFlow 텐서 기초
# pip install tensorflow

import tensorflow as tf

# 텐서 생성
zeros = tf.zeros([3, 4])
ones = tf.ones([2, 3, 4])
rand = tf.random.uniform([3, 3])
constant = tf.constant([[1, 2], [3, 4]])

# 텐서 속성
print(f"Shape: {rand.shape}")
print(f"Dtype: {rand.dtype}")

# 딥러닝 모델에서의 텐서 흐름 예시
# 이미지 배치: [batch_size, height, width, channels]
batch_images = tf.random.normal([32, 224, 224, 3])

# 컨볼루션 레이어 시뮬레이션
conv_layer = tf.keras.layers.Conv2D(64, (3, 3), padding='same')
output = conv_layer(batch_images)
print(f"입력: {batch_images.shape}")  # (32, 224, 224, 3)
print(f"출력: {output.shape}")        # (32, 224, 224, 64)

# Mixed Precision (FP16) 예시
tf.keras.mixed_precision.set_global_policy('mixed_float16')
print(f"Global Policy: {tf.keras.mixed_precision.global_policy()}")

# 텐서 타입 변환
float_tensor = tf.cast(constant, tf.float32)
int_tensor = tf.cast(rand * 10, tf.int32)

# GPU 메모리 확인
gpus = tf.config.list_physical_devices('GPU')
print(f"사용 가능한 GPU: {len(gpus)}개")

📊 Performance & Cost

Tensor operation performance comparison as of January 2025.

Hardware FP32 TFLOPS FP16 TFLOPS Memory Price (approximate)
NVIDIA H100 67 1,979 80GB HBM3 $30,000+
NVIDIA A100 19.5 312 80GB HBM2e $10,000+
NVIDIA RTX 4090 82.6 165 24GB GDDR6X $1,600
Apple M3 Max ~14 ~28 128GB unified $3,000+

Memory usage by data type:

Data Type Vite Use case Memory Savings
float32 (FP32) 32bit Basic Training Baseline
float16 (FP16) 16bit Mixed Precision 50%
bfloat16 (BF16) 16bit LLM Training 50%
int8 8bit Quantized Inference 75%

🗣️ Say It Like This in Practice

💬 In a Meeting
"We resolved the GPU out-of-memory issue by changing the tensor data type to BF16 and applying gradient checkpointing. Even if we increase the batch size from 32 to 64, OOM no longer occurs."
💬 In an Interview
"Whether a tensor is contiguous matters a lot for performance. After transpose or permute, the memory layout becomes non-contiguous, and computing in that state slows things down, so call .contiguous() when necessary."
💬 In a Technical Discussion
"With torch.compile(), tensor operations are automatically optimized. They are compiled into Triton kernels, and in some cases they run more than 2x faster without manual CUDA optimization. However, if there are many dynamic shapes, there is compilation overhead."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌

Mixed CPU-GPU tensor operations

Directly operating on a CPU tensor and a GPU tensor causes an error. Before operating, check that all tensors are on the same device, and unify them with .to(device).

❌

Side effects of in-place operations

In-place operations such as a.add_(b) can corrupt the autograd graph. Be especially careful with tensors where requires_grad=True.

✅

The right approach

Explicitly specify device and dtype when creating tensors. Use memory profiling tools (torch.cuda.memory_summary()) to detect memory leaks early.

🔗 Related Terms

📚 Learn More