Weight
Weight
Learnable parameters that represent the strength of neural network connections. The core element a model learns from data.
Weight
Learnable parameters that represent the strength of neural network connections. The core element a model learns from data.
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.
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):,}")
"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."
"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."
"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
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.
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.
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.