πŸ€– AI/ML

Weight

Weight

Learnable parameters that represent the strength of neural network connections. The core element a model learns from data.

πŸ“– Detailed Explanation

A weight is a numerical value that represents the strength of a connection between neurons in a neural network. Input data is multiplied by weights, summed, and passed to the next layer, and these weights are precisely what the model "learns." When GPT-4 is said to have 1.8 trillion parameters, most of them are these weights.

The concept of weights began with Frank Rosenblatt's perceptron in 1958. Initially they were the coefficients of a simple linear classifier, but in the deep learning era, billions to trillions of weights learn complex patterns. The advancement of weight update algorithms (backpropagation + gradient descent) was the core of the deep learning revolution.

How weights work is simple. Neuron output = activation function(input1*weight1 + input2*weight2 + ... + bias). During training, the weights are updated little by little in the direction that minimizes the loss function. This process is repeated millions of times, and the weights gradually come to represent the patterns in the data.

In practice, weights are saved as model files (.pt, .safetensors, .bin). Pretrained weights are loaded for fine-tuning, or weights are shared to deploy models. The model files you download from Hugging Face are precisely collections of these weights. Quantization is also used to lower weight precision and reduce model size.

πŸ’» Code Example

import torch
import torch.nn as nn

# 1. κ°„λ‹¨ν•œ 신경망 μ •μ˜
class SimpleNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(10, 5)  # 10 μž…λ ₯ -> 5 좜λ ₯
        self.fc2 = nn.Linear(5, 2)   # 5 μž…λ ₯ -> 2 좜λ ₯

    def forward(self, x):
        x = torch.relu(self.fc1(x))
        return self.fc2(x)

model = SimpleNN()

# 2. κ°€μ€‘μΉ˜ 확인
print("=== fc1 λ ˆμ΄μ–΄ κ°€μ€‘μΉ˜ ===")
print(f"κ°€μ€‘μΉ˜ shape: {model.fc1.weight.shape}")  # [5, 10]
print(f"편ν–₯ shape: {model.fc1.bias.shape}")      # [5]
print(f"κ°€μ€‘μΉ˜ κ°’ (일뢀):\n{model.fc1.weight[:2, :3]}")

# 3. 전체 νŒŒλΌλ―Έν„° 수 계산
total_params = sum(p.numel() for p in model.parameters())
trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f"\n총 νŒŒλΌλ―Έν„°: {total_params:,}")
print(f"ν•™μŠ΅ κ°€λŠ₯ νŒŒλΌλ―Έν„°: {trainable_params:,}")

# 4. κ°€μ€‘μΉ˜ μ΄ˆκΈ°ν™”
def init_weights(m):
    if isinstance(m, nn.Linear):
        nn.init.xavier_uniform_(m.weight)
        nn.init.zeros_(m.bias)

model.apply(init_weights)
print(f"\nμ΄ˆκΈ°ν™” ν›„ κ°€μ€‘μΉ˜:\n{model.fc1.weight[:2, :3]}")

# 5. κ°€μ€‘μΉ˜ μ €μž₯ & λ‘œλ“œ
torch.save(model.state_dict(), "model_weights.pt")
print("\nκ°€μ€‘μΉ˜ μ €μž₯ μ™„λ£Œ: model_weights.pt")

# μƒˆ λͺ¨λΈμ— κ°€μ€‘μΉ˜ λ‘œλ“œ
new_model = SimpleNN()
new_model.load_state_dict(torch.load("model_weights.pt"))
print("κ°€μ€‘μΉ˜ λ‘œλ“œ μ™„λ£Œ!")

# 6. ν•™μŠ΅ 쀑 κ°€μ€‘μΉ˜ λ³€ν™” κ΄€μ°°
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
criterion = nn.CrossEntropyLoss()

# 더미 데이터
x = torch.randn(32, 10)
y = torch.randint(0, 2, (32,))

print(f"\nν•™μŠ΅ μ „ fc1.weight[0,0]: {model.fc1.weight[0,0].item():.6f}")

# ν•™μŠ΅ μŠ€ν…
for _ in range(10):
    optimizer.zero_grad()
    output = model(x)
    loss = criterion(output, y)
    loss.backward()
    optimizer.step()

print(f"ν•™μŠ΅ ν›„ fc1.weight[0,0]: {model.fc1.weight[0,0].item():.6f}")

# 7. κ°€μ€‘μΉ˜ 프리징 (일뢀 λ ˆμ΄μ–΄ ν•™μŠ΅ 쀑지)
for param in model.fc1.parameters():
    param.requires_grad = False

print(f"\nfc1 프리징 ν›„ ν•™μŠ΅ κ°€λŠ₯ νŒŒλΌλ―Έν„°: {sum(p.numel() for p in model.parameters() if p.requires_grad):,}")

πŸ—£οΈ Say It Like This in Practice

πŸ’¬ In a Meeting

"This model's weight file is 14GB, but INT4 quantization can reduce it to 3-4GB. Accuracy drops slightly, but inference gets faster and it uses less GPU memory."

πŸ’¬ In an Interview

"What's the difference between weights and parameters?" - "Weights are the connection strengths between layers, and parameters are a broader concept that includes both weights and biases. A '70B-parameter model' means weights plus biases total 70 billion."

πŸ’¬ In a Technical Discussion

"LoRA freezes the pretrained weights and trains only low-rank adapters. Since it adds delta weights BA to the original weights W, the number of trained parameters is less than 0.1% of full fine-tuning."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Common Mistakes & Cautions

❌
Ignoring Weight Initialization

If you initialize all weights to 0 or the same value, training fails due to the symmetry problem. Use an initialization method suited to the layer and activation function, such as Xavier or He initialization.

❌
Confusing Weight File Formats

There are various formats, such as .pt (PyTorch), .safetensors (a safe format), .bin (Hugging Face), and .ckpt (checkpoint). Compatibility issues exist, so check how to load them. safetensors is recommended because it has no pickle vulnerabilities.

βœ…
Using Gradient Checkpointing

When training large models, you can save a lot of memory by recomputing intermediate activations during backpropagation instead of storing them. Training becomes slower, but it makes it possible to train with larger batches or larger models.

πŸ”— Related Terms

πŸ“š Learn More