Loading...
Loading...
Compare original and translation side by side
KISS > Complexity | Simple solutions that work > clever solutions that break
Readability > Brevity | Code is read 10x more than written
Explicit > Implicit | No magic, no hidden behavior
Tested > Assumed | If it's not tested, it's broken
Reproducible > Fast | Random seeds, deterministic ops, version pinning简洁至上 > 过度复杂 | 可用的简单方案 > 易出问题的巧妙方案
可读性 > 简洁性 | 代码的阅读次数是编写次数的10倍
显式 > 隐式 | 无魔法操作,无隐藏行为
经过测试 > 主观假设 | 未测试的代码即为有问题的代码
可复现 > 快速 | 随机种子、确定性操作、版本固定| Task | Primary Choice | When to Use Alternative |
|---|---|---|
| Deep Learning | PyTorch | TensorFlow for production TPU, JAX for research |
| Tabular ML | scikit-learn | XGBoost/LightGBM for large data, CatBoost for categoricals |
| Computer Vision | torchvision + timm | detectron2 for detection, ultralytics for YOLO |
| NLP/LLM | transformers (HuggingFace) | vLLM for serving, llama.cpp for edge |
| Data Processing | pandas | polars for >10GB, dask for distributed |
| Experiment Tracking | MLflow | W&B for teams, Neptune for enterprise |
| Hyperparameter Tuning | Optuna | Ray Tune for distributed |
| 任务 | 首选 | 何时使用替代方案 |
|---|---|---|
| 深度学习 | PyTorch | 生产环境使用TPU时选TensorFlow,研究场景选JAX |
| 表格数据ML | scikit-learn | 大数据量选XGBoost/LightGBM,含分类特征选CatBoost |
| 计算机视觉 | torchvision + timm | 目标检测选detectron2,YOLO系列选ultralytics |
| NLP/LLM | transformers (HuggingFace) | 服务部署选vLLM,边缘设备选llama.cpp |
| 数据处理 | pandas | 数据量>10GB选polars,分布式处理选dask |
| 实验跟踪 | MLflow | 团队协作选W&B,企业级场景选Neptune |
| 超参数调优 | Optuna | 分布式调优选Ray Tune |
Classification (images) → ResNet/EfficientNet (simple), ViT (SOTA)
Object Detection → YOLOv8 (speed), DETR (accuracy), RT-DETR (balanced)
Segmentation → U-Net (medical), Mask2Former (general), SAM (zero-shot)
Text Classification → DistilBERT (fast), RoBERTa (accuracy)
Text Generation → Llama/Mistral (open), GPT-4 (quality)
Embeddings → sentence-transformers, text-embedding-3-large
Time Series → TSMixer, PatchTST, temporal fusion transformer
Tabular → XGBoost (general), TabNet (interpretable), FT-Transformer
Anomaly Detection → IsolationForest (simple), AutoEncoder (deep)
Recommendation → Two-tower, NCF, LightFM (cold start)图像分类 → ResNet/EfficientNet(简单易用), ViT(当前最优)
目标检测 → YOLOv8(速度优先), DETR(精度优先), RT-DETR(均衡型)
图像分割 → U-Net(医疗场景), Mask2Former(通用场景), SAM(零样本)
文本分类 → DistilBERT(快速), RoBERTa(精度高)
文本生成 → Llama/Mistral(开源), GPT-4(质量优)
嵌入向量 → sentence-transformers, text-embedding-3-large
时间序列 → TSMixer, PatchTST, 时间融合Transformer
表格数据 → XGBoost(通用), TabNet(可解释), FT-Transformer
异常检测 → IsolationForest(简单), AutoEncoder(深度学习方案)
推荐系统 → 双塔模型, NCF, LightFM(冷启动场景)project/
├── pyproject.toml # Dependencies, build config (NO setup.py)
├── .env.example # Environment template
├── .gitignore
├── Makefile # Common commands
├── README.md
├── src/
│ └── {project_name}/
│ ├── __init__.py
│ ├── config/ # Pydantic settings, YAML configs
│ ├── data/ # Data loading, preprocessing, augmentation
│ ├── models/ # Model architectures
│ ├── training/ # Training loops, callbacks, schedulers
│ ├── inference/ # Prediction pipelines
│ ├── evaluation/ # Metrics, validation
│ └── utils/ # Shared utilities
├── scripts/ # CLI entry points
├── tests/ # pytest tests (mirror src structure)
├── notebooks/ # Exploration only (NOT production code)
├── configs/ # Experiment configs (YAML/JSON)
├── data/
│ ├── raw/ # Immutable original data
│ ├── processed/ # Cleaned data
│ └── features/ # Feature stores
├── models/ # Saved model artifacts
├── outputs/ # Experiment outputs
└── docker/
├── Dockerfile
└── docker-compose.ymlproject/
├── pyproject.toml # 依赖项、构建配置(禁止使用setup.py)
├── .env.example # 环境变量模板
├── .gitignore
├── Makefile # 常用命令集合
├── README.md
├── src/
│ └── {project_name}/
│ ├── __init__.py
│ ├── config/ # Pydantic配置、YAML配置文件
│ ├── data/ # 数据加载、预处理、增强
│ ├── models/ # 模型架构定义
│ ├── training/ # 训练循环、回调函数、学习率调度器
│ ├── inference/ # 预测流水线
│ ├── evaluation/ # 指标计算、验证逻辑
│ └── utils/ # 通用工具函数
├── scripts/ # CLI入口脚本
├── tests/ # pytest测试用例(与src结构镜像对应)
├── notebooks/ # 仅用于探索性分析(禁止用于生产代码)
├── configs/ # 实验配置文件(YAML/JSON格式)
├── data/
│ ├── raw/ # 不可修改的原始数据
│ ├── processed/ # 清洗后的数据
│ └── features/ # 特征存储
├── models/ # 保存的模型 artifacts
├── outputs/ # 实验输出结果
└── docker/
├── Dockerfile
└── docker-compose.yml| Reference | When to Load |
|---|---|
| references/deep-learning.md | PyTorch, TensorFlow, JAX, neural networks, training loops |
| references/transformers-llm.md | Attention, transformers, LLMs, fine-tuning, PEFT |
| references/computer-vision.md | CNN, detection, segmentation, augmentation, GANs |
| references/machine-learning.md | sklearn, XGBoost, feature engineering, ensembles |
| references/nlp.md | Text processing, embeddings, NER, classification |
| references/mlops.md | MLflow, Docker, deployment, monitoring |
| references/clean-code.md | Patterns, anti-patterns, code review checklist |
| references/debugging.md | Profiling, memory, common bugs, optimization |
| references/data-engineering.md | pandas, polars, dask, preprocessing |
| 参考文件 | 加载场景 |
|---|---|
| references/deep-learning.md | PyTorch、TensorFlow、JAX、神经网络、训练循环相关任务 |
| references/transformers-llm.md | 注意力机制、Transformer、LLM、微调、PEFT相关任务 |
| references/computer-vision.md | CNN、目标检测、图像分割、数据增强、GAN相关任务 |
| references/machine-learning.md | sklearn、XGBoost、特征工程、集成学习相关任务 |
| references/nlp.md | 文本处理、嵌入向量、NER、文本分类相关任务 |
| references/mlops.md | MLflow、Docker、模型部署、监控相关任务 |
| references/clean-code.md | 设计模式、反模式、代码审查清单相关任务 |
| references/debugging.md | 性能分析、内存优化、常见问题排查、模型优化相关任务 |
| references/data-engineering.md | pandas、polars、dask、数据预处理相关任务 |
def train_model(
model: nn.Module,
train_loader: DataLoader,
optimizer: torch.optim.Optimizer,
epochs: int = 10,
device: str = "cuda",
) -> dict[str, list[float]]:
...def train_model(
model: nn.Module,
train_loader: DataLoader,
optimizer: torch.optim.Optimizer,
epochs: int = 10,
device: str = "cuda",
) -> dict[str, list[float]]:
...from pydantic import BaseModel, Field
class TrainingConfig(BaseModel):
learning_rate: float = Field(1e-4, ge=1e-6, le=1.0)
batch_size: int = Field(32, ge=1)
epochs: int = Field(10, ge=1)
seed: int = 42
model_config = {"frozen": True} # Immutablefrom pydantic import BaseModel, Field
class TrainingConfig(BaseModel):
learning_rate: float = Field(1e-4, ge=1e-6, le=1.0)
batch_size: int = Field(32, ge=1)
epochs: int = Field(10, ge=1)
seed: int = 42
model_config = {"frozen": True} # 配置不可修改import structlog
logger = structlog.get_logger()import structlog
logger = structlog.get_logger()undefinedundefinedundefinedundefinedundefinedundefineddef train_epoch(
model: nn.Module,
loader: DataLoader,
optimizer: torch.optim.Optimizer,
criterion: nn.Module,
device: torch.device,
scaler: GradScaler | None = None,
) -> float:
model.train()
total_loss = 0.0
for batch in tqdm(loader, desc="Training"):
optimizer.zero_grad(set_to_none=True) # More efficient
inputs = batch["input"].to(device, non_blocking=True)
targets = batch["target"].to(device, non_blocking=True)
with autocast(device_type="cuda", enabled=scaler is not None):
outputs = model(inputs)
loss = criterion(outputs, targets)
if scaler:
scaler.scale(loss).backward()
scaler.unscale_(optimizer)
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
scaler.step(optimizer)
scaler.update()
else:
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()
total_loss += loss.item()
return total_loss / len(loader)def train_epoch(
model: nn.Module,
loader: DataLoader,
optimizer: torch.optim.Optimizer,
criterion: nn.Module,
device: torch.device,
scaler: GradScaler | None = None,
) -> float:
model.train()
total_loss = 0.0
for batch in tqdm(loader, desc="Training"):
optimizer.zero_grad(set_to_none=True) # 更高效的梯度清零方式
inputs = batch["input"].to(device, non_blocking=True)
targets = batch["target"].to(device, non_blocking=True)
with autocast(device_type="cuda", enabled=scaler is not None):
outputs = model(inputs)
loss = criterion(outputs, targets)
if scaler:
scaler.scale(loss).backward()
scaler.unscale_(optimizer)
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
scaler.step(optimizer)
scaler.update()
else:
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()
total_loss += loss.item()
return total_loss / len(loader)torch.manual_seednp.random.seedrandom.seedmodel.eval()torch.no_grad()nvidia-smitorch.cuda.memory_summary()torch.manual_seednp.random.seedrandom.seedmodel.eval()torch.no_grad()nvidia-smitorch.cuda.memory_summary()| Anti-Pattern | Correct Approach |
|---|---|
| Explicit imports |
| Hardcoded paths | Config files or environment variables |
| Structured logging |
| Nested try/except | Handle specific exceptions |
| Global mutable state | Dependency injection |
| Magic numbers | Named constants |
| Jupyter in production | |
| Always |
| 反模式 | 正确做法 |
|---|---|
| 显式导入所需模块 |
| 硬编码路径 | 使用配置文件或环境变量 |
| 使用结构化日志 |
| 嵌套try/except | 捕获特定异常类型 |
| 全局可变状态 | 使用依赖注入 |
| 魔法数字 | 使用命名常量 |
| Jupyter Notebook用于生产 | 使用结构规范的 |
| 始终设置 |
torch.compiletorch.compile