1. ๐ฅ Tensors & Autograd
Stop writing backprop by hand.
requires_grad=True tracks every operation โ .backward() applies the chain rule automatically.
import torch
x = torch.tensor(2.0)
y = torch.tensor(5.0)
w = torch.tensor(0.5, requires_grad=True)
b = torch.tensor(0.1, requires_grad=True)
pred = w * x + b
loss = (pred - y) ** 2
loss.backward()
print(w.grad.item(), b.grad.item())โ Exact gradients, zero math errors.
2. โ๏ธ The
__call__ MethodWhy model(x) works, not model.forward(x). call runs hooks before forward.
class LinearLayer:
def __init__(self, w, b):
self.w, self.b = w, b
self._hooks = []
def __call__(self, x):
for hook in self._hooks:
hook(x)
return self.forward(x)
def forward(self, x):
return x * self.w + self.bโ ๏ธ Always call model(x) โ .forward() skips hooks โ silent bugs.
3. ๐พ Pickle vs ONNX
pickle = Python-locked + code execution risk ๐จ. ONNX = static, language-agnostic graph.
import torch
model.eval()
dummy_input = torch.randn(1, 10)
torch.onnx.export(
model, dummy_input, "model.onnx",
export_params=True,
opset_version=15,
input_names=["input"],
output_names=["output"],
dynamic_axes={"input": {0: "batch_size"}})
โ Portable, fast, decoupled from training code.
4. ๐งฑ Abstract Base Classes
@abstractmethod forces subclasses to implement methods. Miss one โ fails at startup, not mid-request.
from abc import ABC, abstractmethod
class ModelInterface(ABC):
@abstractmethod
def predict(self, x: list) -> list: ...
@abstractmethod
def get_metadata(self) -> dict: ...โ Fail fast, fail safe.
5. ๐ Env Variables & Secrets
Never hardcode keys. Store in .env, gitignore it, load with python-dotenv.
import os
from dotenv import load_dotenv
load_dotenv()
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
raise ValueError("OPENAI_API_KEY is not set!")
โ
Same code locally + Docker/Lambda. Zero leaks.โค๏ธ Follow AIJobs for more AI drops